【问题标题】:UITextView that expands dynamically to text inside a scroll view using auto layoutUITextView 使用自动布局动态扩展为滚动视图内的文本
【发布时间】:2013-06-11 09:12:11
【问题描述】:

我有一个包含一些组件的UIScrollView,其中一个组件是UITextView,我想要的是让UITextViewUIScrollView 一起动态扩展,实际上我使用autoLayout ,所以这段代码不起作用:

    CGRect frame = self.detailTextView.frame;
    frame.size.height = self.detailTextView.contentSize.height;
    self.detailTextView.frame = frame;
    scroll.contentSize = CGSizeMake(scroll.contentSize.width,
                                    300 + self.detailTextView.frame.size.height);
    [self.detailTextView setFrame:frame];

我想要的是用故事板元素帮助我做到这一点。

【问题讨论】:

    标签: ios uiscrollview uitextview autolayout


    【解决方案1】:

    不要设置框架,而是将文本视图的高度约束之一拖到控制器中以创建出口。然后在 viewWillLayoutSubviews 中抓取 contentSize 并设置文本视图高度约束的常量。这应该完成您在上面的代码中对框架所做的事情。只需确保您的文本视图从所有边缘到滚动视图都有约束,以便滚动视图可以正确调整自身大小。

    【讨论】:

    • 这有点工作,但是他们的约束被改变得太晚了,所以你可以在视图加载后实际看到它在移动。有没有办法解决这个问题?
    • 设置文本后设置高度约束。 self.textviewHeightConstraint.constant = self.textview.contentSize.height;
    【解决方案2】:

    在我的情况下,我所做的是将滚动视图保留为超级视图并为子视图添加所有约束,并且 uitextview 具有从所有边缘到滚动视图的约束。然后更新 -viewDidLayoutSubviews 方法中的内容大小。这是代码sn-p:

    -(void)viewDidLayoutSubviews{
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
    
        CGRect rect = [_detailText.text boundingRectWithSize:CGSizeMake(_detailText.frame.size.width - 10.0, MAXFLOAT)
                                                 options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                              attributes:attributes
                                                 context:nil];
        CGRect frame = _detailText.frame;
        frame.size.height = ceil(rect.size.height) + _detailText.textContainerInset.top +             _detailText.textContainerInset.bottom;
        _detailText.frame = frame;
        _detailText.contentSize = CGSizeMake(_detailText.frame.size.width, _detailText.frame.size.height);
        [_contentScrollView setContentSize:CGSizeMake(_contentScrollView.frame.size.width, _detailText.frame.origin.y + _detailText.frame.size.height)];
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多