【问题标题】:UITextView within UIScrollView - Dynamic Heights?UIScrollView 中的 UITextView - 动态高度?
【发布时间】:2013-12-19 08:19:26
【问题描述】:

我有一个 UIView,其中包含一个 UIScroller - 它又包含几个标签、一个图像和一个动态文本视图。

文本视图可以包含从几个字符到 2000 个单词的任何内容 - 如何自动将相关高度应用到 UITextView 和父滚动条?

我已经得到了以下 -

//Set Scroller
[self.scrollerArticle setScrollEnabled:YES];
[self.scrollerArticle setContentSize:CGSizeMake(320, 750)];
[self.articleUITextView sizeToFit];
[self.articleUITextView layoutIfNeeded];

但不知道如何将 sizetofit 方法应用于滚动条?

【问题讨论】:

    标签: ios uiscrollview height uitextview


    【解决方案1】:

    您可以使用以下方法获取内容的高度。

    -(CGFloat)getContentHeight{
    
    NSString *aMessage = @"My Name is ABC"; // Can be anything between 0 to 2000 chars
    
    CGSize maximumSize = CGSizeMake(320, 9999);
    
    // Use the font you are willing to use for TexTView.
    UIFont *textFont = [UIFont fontWithName:@"Helvetica-Bold" size:MessageFontSize];
    CGSize myStringSize = [aMessage sizeWithFont:textFont
                       constrainedToSize:maximumSize
                           lineBreakMode:NSLineBreakByWordWrapping];
    
    return myStringSize.height;
    }
    

    然后可以相应地设置Scrollview的ContentSize。

    【讨论】:

      【解决方案2】:

      UITextView 是 UIScrollView 的子类,您应该在设置文本后使用内容大小来获取大小:

      self.articleUITextView.text = @"YOUR TEXT";
      CGRect rec = self.articleUITextView.frame;
      rec.size.height = self.articleUITextView.contentSize.height;
      textView.frame = rec;
      

      之后,您可以选择滚动视图的 contentSize。 如果你想使用 sizeWithFont: 它适用于 UILabels 但对于 UITextView 不是必需的。

      【讨论】:

        【解决方案3】:

        这样试试,

        [self.scrollerArticle setContentSize:CGSizeMake(320, CGRectGetMaxY(self.articleUITextView.frame))];
        

        【讨论】:

        • 要补充这一点,你应该在调用sizeToFit函数之后调用上面的代码行,因为你会在使用它后得到一个新的UITextView框架。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 2017-10-26
        • 1970-01-01
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多