在UItextview上设置动态高度以编程方式拟合内容

时间:2016-02-06 03:18:58

标签: ios swift uitextview

只需通过编程编码,我就可以尝试实现类似下图的功能。 TextView和ContainerView嵌入在scrollview中,尽管它没有显示在图像中。

enter image description here

这是我的代码。

override func viewDidLoad() {
    super.viewDidLoad()
    let margin = CGFloat(10)
    textView =  UITextView()
    textView.text = "asdadaasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadaadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadadasdadadaddadd"
let contentSize = textView.sizeThatFits(textView.bounds.size)
textView.frame = CGRectMake(margin, 0, self.view.frame.width - 2 * margin, contentSize.height)


let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 50))
let containerView = UIView(frame: CGRectMake(margin, contentSize.height + margin, self.view.frame.width - 2 * margin, self.view.frame.height))

let button1 = UIButton(frame:  CGRectMake(margin, contentSize.height + containerView.frame.height + 2 * margin, (view.frame.width - 2 * margin)/2, 30))

scrollView.contentSize = CGSize(width: self.view.frame.width, height: button1.frame.origin.y + button1.frame.height + margin)

self.view.addSubview(scrollView)
scrollView.addSubview(textView)
scrollView.addSubview(containerView)

scrollView.backgroundColor = UIColor.blueColor()
containerView.backgroundColor = UIColor.yellowColor()
textView.backgroundColor = UIColor.greenColor()
}

问题是textview的高度不是动态的,无法在textview中显示所有内容。

我已经确认,如果我在viewdidappear中添加以下代码,它会使textview的高度动态,但它会堆叠在Container视图下,因为以下代码在ViewDidLoad配置完所有内容后运行。

let contentSize = textView.sizeThatFits(textView.bounds.size)
textView.frame = CGRectMake(margin, 0, self.view.frame.width - 2 * margin, contentSize.height)

这种问题的最佳方法是什么? 我认为这是由于viewdidload中的渲染顺序引起的,但我并非100%肯定。如果有人可以谈论渲染顺序,那就太好了。

1 个答案:

答案 0 :(得分:1)

要回答原始问题,您对 sizeThatFits 的调用不知道TextView应该有多高,因为它不知道您希望它有多宽。我想在 sizeThatFits 之前您需要以下内容:

textView.frame.size.width = self.view.frame.width - 2 * margin