问题描述
仅通过编程编码,我正在尝试实现如下图所示的内容.TextView 和 ContainerView 嵌入在滚动视图中,尽管它没有显示在图像中.
Just by programmatically coding, I'm trying to achieve something like below image. TextView and ContainerView are embedded in scrollview although it is not shown in the image.
这是我的代码.
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 中的所有内容.
The problem is that textview's height is not dynamic to show all content in textview.
我已经确认,如果我在 viewdidappear 中添加以下代码,它确实使 textview 的高度动态但它堆叠在容器视图下,因为下面的代码在 ViewDidLoad 配置完所有内容后运行.
I've confirmed that if I add below code in viewdidappear, it does make the height of textview dynamic but it is stacked under Container view because below code runs after ViewDidLoad configured everything.
let contentSize = textView.sizeThatFits(textView.bounds.size)
textView.frame = CGRectMake(margin, 0, self.view.frame.width - 2 * margin, contentSize.height)
解决此类问题的最佳方法是什么?我认为这是由于 viewdidload 中的渲染顺序引起的,但我不是 100% 确定.如果有人也能谈论渲染顺序就好了.
What would be the best approach for this kind of problem?I think this is caused due to rendering order in viewdidload but I'm not 100% sure. It would be great if someone can talk about rendering order too.
推荐答案
为了回答最初的问题,您对 sizeThatFits 的调用不知道 TextView 应该有多高,因为它不知道有多宽你想要它.我认为在 sizeThatFits 行之前,您需要以下内容:
To answer the original question, your call to sizeThatFits has no idea how tall the TextView should be because it has no idea how wide you want it to be. I think before the sizeThatFits line you want the following:
textView.frame.size.width = self.view.frame.width - 2 * margin
这篇关于以编程方式在 UItextview 上设置动态高度以适应内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!