开发者

UITextField editing partial string

I would like to be able to edit text in a UITextField like this: "First part[]second part"

  • the part between the brackets should be edited
  • if I tapped the textfield and typed "foo", it should look like: "First part[foo]second part"
  • i would like the text to act if you were just writing in the middle of some text
  • 开发者_开发知识库
  • the user should not be able to edit the first and second part

My first approach (after some searching) was to use the textfields leftView for the "first part" and rightView for the "second part", both with a uilabel subview with the text. But I can't seem to get the positioning right. Especially getting it to fit dynamically...

Am I on the right track? Is there a more elegant way of doing this? Any help is appreciated, thanks.


There is a method in the UITextField delegate protocol that should do exactly what you want:

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

If the "first part" and "second part" are not to change, you can set up the range based on them, i.e. setting the beginning of your range as the end of "first part" and the end of your range to be the total length of the string minus the length of "second part"


To get the width of the middle UITextField, you can use NSString's - (CGSize)sizeWithFont:(UIFont *)font and use that to set the size of the UITextField. Once you know its frame, you can position the two other UILabel's frames.

Another option might just to be to have one string, but force the entry point to be between the [] and prohibit attempts to try to set it outside that range.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜