gpt4 book ai didi

ios - 如何限制 UITextView 中的行数?

转载 作者:IT王子 更新时间:2023-10-29 05:39:32 29 4
gpt4 key购买 nike

我的屏幕上有一个 UITextView,用户应该只填写两行,当用户在第二行时,返回键应该变成完成

如何限制 UITextView 中的行数?我搜索了很多,没有一个有用的结果!

我为 Swift 找到了这个答案:

locationNoteTextView.textContainer.maximumNumberOfLines = 2
self.locationNoteTextView.textContainer.lineBreakMode = NSLineBreakMode.ByClipping

没用,这样用户可以输入无限字符,但是在屏幕上看到的只是两行!

因此,如果您尝试打印 textView 的文本,您会发现一个灾难文本。

最佳答案

您需要实现 textView:shouldChangeTextInRange:replacementText:。只要文本要更改,就会调用此方法。您可以使用文本属性访问 TextView 的当前内容。

使用 [textView.text stringByReplacingCharactersInRange:range withString:replacementText] 从传递的范围和替换文本构建新内容。

然后您可以计算行数并返回 YES 以允许更改或返回 NO 以拒绝它。

编辑:根据 OP 要求:

swift :

func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
}


func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
var textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;

let boundingRect = sizeOfString(newText, constrainedToWidth: Double(textWidth), font: textView.font!)
let numberOfLines = boundingRect.height / textView.font!.lineHeight;

return numberOfLines <= 2;
}

Obj-C

- (CGSize) sizeOfString:(NSString*)str constrainedToWidth:(CGFloat)width andFont:(UIFont*)font
{
return [str boundingRectWithSize:CGSizeMake(width, DBL_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: font}
context:nil].size;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
CGFloat textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset));
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;
CGSize boundingRect = [self sizeOfString:newText constrainedToWidth:textWidth andFont:textView.font];
int numberOfLines = boundingRect.height / textView.font.lineHeight;
return numberOfLines <= 2;
}

关于ios - 如何限制 UITextView 中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32889495/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com