iOS(Swift) TextField限制输入文本的长度(不是字数)

最近做项目有一个特殊需求,就是需要限制一个TextField的输入文本的长度在一定范围内(注意,不是字数),上网查了一圈没有找到类似文章,这里把我的方法写进来,mark一下:

1、对TextField添加监听函数:

1
textField . addTarget ( self action "textFieldTextDidChange:" forControlEvents UIControlEvents . EditingChanged )

2、在输入内容变化时进行处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func  textFieldTextDidChange ( textField : UITextField ) {
     if  let  _  textField . text  {
         if  let  positionRange  textField . markedTextRange  {
             if  let  _  textField . positionFromPosition ( positionRange . start offset 0 ) {
                 //正在使用拼音,不进行校验
             else  {
                 //不在使用拼音,进行校验
                 self . checkTextFieldLengthAndModify ( textField )
             }
         else  {
             //不在使用拼音,进行校验
             self . checkTextFieldLengthAndModify ( textField )
         }
     }
}

3、实现校验方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//检查输入框的文字是否超长,如果超出长度则做截短
func  checkTextFieldLengthAndModify ( textField : UITextField ) {
     if  let  text  textField . text  {
         if  self . checkTextFielLength ( textField str text ) {
             //长度正常,不处理
         else  {
             //超出长度,开始处理
             self . view . makeToastCenter ( "输入文字过长" )
             
             let  len  text . length
             let  txt  text  as  NSString
             if  len  >  0  {
                 //进行截短,看是否超长,如果不超长,则继续截短,直到不超长为止
                 //Exp:
                 //apple
                 //appl
                 //app
                 for  var  i  len - 1 i  > 0 i -- {
                     let  txt_s  txt . substringToIndex ( i )
                     //print("txt_s : \(txt_s)")
                     if  self . checkTextFielLength ( textField str txt_s ) {
                         //就截取到这了
                         textField . text  txt_s
                         break
                     else  {
                         //继续截取
                     }
                 }
             }
         }
     }
}

4、实现checkTextFielLength,判断文字是否超出输入框长度

1
2
3
4
5
6
7
8
func  checkTextFielLength ( textField UITextField str NSString ) - >  Bool  {
     let  rect  str . boundingRectWithSize ( CGSizeMake ( CGFloat ( MAXFLOAT ),  CGFloat ( MAXFLOAT )),  options : . UsesLineFragmentOrigin attributes textField . defaultTextAttributes context nil )
     if  rect . width  >  textField . width  {
         return  false
     else  {
         return  true
     }
}

 

这里的长度限制是根据UITextField的长度来限制的,你也可以根据自己的需求来设定限制的长度。

 

转载于:https://www.cnblogs.com/Hakim/p/6513495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值