ios - 如何根据数据动态调整UITextView和scrollview

标签 ios swift

enter image description here

在我的项目中,我必须根据数据动态调整 UItextview 和 UIScrollView 我尝试了很多,但完美的结果还没有到来,请帮助我。

查看我的基于数据增长textview的代码,我不知道如何基于数据增长UIScrollView,请有人帮助我。

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

最佳答案

您可以将textview框架的大小设置为

CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame=frame;

或者您可以尝试下面的代码。

- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
   return size.height;
}

或者您甚至可以尝试下面的代码。

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

    NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };

    CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];

关于ios - 如何根据数据动态调整UITextView和scrollview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31333822/

相关文章:

ios - 快速添加动画序列

ios - 如何计算 MKMapView 中可见区域的半径?

ios - 在 ios swift 中为小节创建页脚

ios - 从 iOS 项目包中读取 plist 文件

iphone - PhoneGap + iOS 防止默认滚动操作从输入文本字段开始

ios - 从 XML Parse 匹配 NSDictionary

iOS - 如何使用 OpenGLES 创建自定义 GPUImageFilters

swift - 如何快速将 UITableViewCell 数据发送到另一个 ViewController?

ios - 删除 UITableViewCell 时更新 firebase 中的数据

ios - fetchedResultsController 不断在每一行中显示相同的实体