最近做项目有一个特殊需求,就是需要限制一个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的长度来限制的,你也可以根据自己的需求来设定限制的长度。