---
title: "[ios]限制textField长度"
author: "119568242"
date: "2013-03-25T17:16:40Z"
tags: []
categories: ["移动开发"]
slug: "ios-textfield"
draft: false
lastmod: "2013-03-25T17:16:40Z"
id: 1836293
url: "https://poolo.iteye.com/blog/1836293"
---

-(BOOL)textField:(UITextField \*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString \*)string{

 

    BOOL result =NO;

 

    if(textField.tag&lt;\[TagUtilgetAirTemperatureTagBase]){

 

        if(range.location&lt;=2){

            return YES;

           

        }else{

            return NO;

        }

    }else{

 

        if(range.location&lt;=1){

 

            return YES;

        }else{

 

            return NO;

        }

    }

    

    return result;

}

 

 

range的location 对应当前修改的字符在字符串的位置 通过限制 最大location可以限制长度

range.length 只是当前修改的长度 并不是当前字符串长度

string 是当前修改的字符(输入或删除的ex:'a' 'c' '1' )