【发布时间】:2019-01-31 06:57:31
【问题描述】:
我正在尝试使用 UITextView 显示具有动态高度的消息,但是当消息的长度足以覆盖屏幕时,我无法获得滚动功能。我尝试了许多在线解决方案,但都失败了。我使用NSMutableAttributedString 来格式化我的文本。
这是我最后一次尝试:
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[self.descString dataUsingEncoding:NSUTF8StringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
__block BOOL found = NO;
[attrStr beginEditing];
[attrStr enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrStr.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
UIFont *newFont = [oldFont fontWithSize:16];
[attrStr addAttribute:NSFontAttributeName value:newFont range:range];
[attrStr addAttribute:NSForegroundColorAttributeName
value:[UIColor darkGrayColor]
range:range];
found = YES;
}
}];
if (!found) {
// No font was found - do something else?
}
[attrStr endEditing];
CGRect labelSize = [attrStr boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
self.textviewHeight.constant = labelSize.size.height;
在 Interface Builder 中,我使用了 UIScrollView,在其中放置了 UIView,在 UIView 中添加了 UITextView。 textviewHeight 是 UITextView 的高度约束。我不敢相信像这样简单的事情花了我这么多小时,我仍然没有解决方案。请帮忙!
我尝试过但失败的其他解决方案:
1.
CGRect labelSize = [self.descString boundingRectWithSize:CGSizeMake(self.view.frame.size.width * 0.97, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
self.descView.frame = CGRectMake(labelSize.origin.x,
labelSize.origin.y,
ceil(labelSize.size.width),
ceil(labelSize.size.height));
[self.descView sizeToFit];
2.
CGRect labelSize = [attrStr boundingRectWithSize:CGSizeMake(self.view.frame.size.width * 0.97, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
CGRect frame = self.descView.frame;
frame.size.height = labelSize.size.height;
self.descView.frame = frame;
如果更容易实现,我不介意使用 UILabel。
【问题讨论】:
-
有点明显......但仍然如此。您是否不小心取消了 IB 中启用滚动的复选框?
-
是的,我做到了。你的意思是在 UITextView 上,对吧?
-
是的。所以检查一下?
-
我已经用这个选项尝试了所有可能的组合。没有任何帮助。
-
组合?当您单击 Attributes Inspector 中的 UITextView 时,Storyboard 上会出现一个名为 Scrolling Enabled 的框。是“开”还是“关”?
标签: ios objective-c xcode uiscrollview