【问题标题】:Disable UITextView when end of line is reached到达行尾时禁用 UITextView
【发布时间】:2013-09-17 10:14:44
【问题描述】:

我创建了一个“UITextView”,而不是设置最大字符限制,我希望在字符到达行尾时禁用键盘。我尝试研究,但找不到答案。好像我是第一个问这个问题的人。

希望你能帮助我。谢谢

【问题讨论】:

  • UITextField 对你有用吗?

标签: objective-c uitextview


【解决方案1】:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

 NSMutableString * mutableString = [NSMutableString stringWithString:textView.text];
[mutableString insertString:text atIndex:textView.text.length];

if (mutableString.length <= desiredLenghtNumber) {
    return YES;

}
else  {
    return NO;
}

}

desiredLenghtNumber 为最大字母数,例如

int desiredLenghtNumber = 10;

当然,您需要将该文本字段设置为委托

textView.delgate = self;

并在 .h 文件中声明此委托

@interface YourViewController : UIViewController <UITextViewDelegate>

【讨论】:

  • 如果原始发布者希望字符在光标到达屏幕右侧时停止,而不是固定数量的字符怎么办?
  • 有获取nsstring宽度的方法。只需检查 nsstring 的宽度是否大于 textview 的宽度。如果是 - 行尾。
  • 你说的是这个方法吗? sizeWithFont?如果我希望字符恰好适合两行,应该如何使用它?获得它的宽度不是我认为的解决方案。
【解决方案2】:

嗯,我想我应该自己回答这个问题。

我试过这段代码,这对我有用。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  NSString *myText = [textView.text stringByReplacingCharactersInRange:range withString:text];

  CGSize textSize = [myText sizeWithFont:textView.font constrainedToSize:CGSizeMake(TEXTVIEW_WIDTH - 20, 10000) lineBreakMode:NSLineBreakByWordWrapping];

  NSInteger strH = textSize.height;
  NSLog(@"String Size Height %i",strH);
  NSInteger maxHeight = 51;

    if (strH >= maxHeight)

    {
      return NO;
    }

   return YES;
}

我在这里的代码中使用了 51,因为当我检查 NSLog 中的 strH 的值时,我发现 51 标志着第三行的开始。我不允许文本达到那个高度,因为我只需要在我的应用程序中允许使用 2 行 UITextView

constrainedToSize:CGSizeMake(TEXTVIEW_WIDTH - 20, 10000) 中,我从UITextView 的宽度中减去了 20 像素,以考虑它的左右边距。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 2018-04-28
    • 2018-06-15
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多