Upv*_*ote 3 xcode objective-c ios4
我有一个文本字段,我想限制可以输入160个字符的文本.此外,我需要一个计数器来获取当前文本长度.
我用NSTimer解决了它:
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self
selector:@selector(countText)
userInfo:nil
repeats:YES];
Run Code Online (Sandbox Code Playgroud)
我用这种方式显示长度:
-(void)countText{
countLabel.text = [NSString stringWithFormat:@"%i",
_textEditor.text.length];
}
Run Code Online (Sandbox Code Playgroud)
这不是最好的计数器解决方案,因为它取决于时间而不取决于keyUp事件.有没有办法捕捉这样的事件和触发方法?
其他的事情是,是否可以阻止/限制文本输入,例如通过在文本字段上提供最大长度参数?
Mat*_*uch 10
这是(或应该是)委托方法的正确版本:
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
NSInteger newTextLength = [aTextView.text length] - range.length + [text length];
if (newTextLength > 160) {
// don't allow change
return NO;
}
countLabel.text = [NSString stringWithFormat:@"%i", newTextLength];
return YES;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11287 次 |
| 最近记录: |