【问题标题】:Can't update UITextView size after setting content height设置内容高度后无法更新 UITextView 大小
【发布时间】:2015-12-14 11:13:18
【问题描述】:

我需要的是在首次启动应用程序时显示的许可协议。简单的 UITextView,文本后带有同意按钮。我需要它的大小等于屏幕大小并且内容可以滚动。这一切都发生在主 ViewController 的 ViewDidLoad() 方法中:

let text = "<p>very very long html text</p>"

var str = NSAttributedString()
do {
   str = try NSAttributedString(data: text.dataUsingEncoding 
   (NSUnicodeStringEncoding, allowLossyConversion: true)!,
   options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
   documentAttributes: nil)   
   }
   catch 
   {
       print(error)
   }

   let licenseView = UITextView(frame:CGRectMake(self.navigationController!.view.frame.origin.x,self.navigationController!.view.frame.origin.y, self.navigationController!.view.frame.size.width, self.navigationController!.view.frame.size.height))
   licenseView.attributedText = str

   licenseView.scrollEnabled = true
   licenseView.editable = false
   licenseView.selectable = true
   licenseView.dataDetectorTypes = .All

   let LVSize:CGSize = licenseView.sizeThatFits(CGSizeMake(licenseView.frame.size.width, CGFloat(FLT_MAX)))

licenseView' 内容高度为 1850.5。需要添加y位置等于1850.5的按钮。

   let button = UIButton(frame:CGRectMake(0, LVSize.height, 300, 50))
   button.setTitle("Agree", forState: .Normal)
   button.backgroundColor = UIColor.blueColor()
   licenseView.addSubview(button)

现在我们需要调整内容的大小以使按钮在文本之后可见

   licenseView.contentSize = CGSizeMake(licenseView.frame.size.width, LVSize.height+300)
   licenseView.setNeedsDisplay()
   licenseView.layoutIfNeeded()


   self.navigationController!.view.addSubview(licenseView)

问题是 contentSize 已更改(如果我 print(licenseView.contentSize) 它将输出 (320.0, 2150.5)),但 textView 的行为仍然像其内容高度为 1850.5 - 当我向下滚动时,我看到该按钮位于可滚动区域之外。我错过了什么?

【问题讨论】:

  • 在添加按钮之前分配文本视图的内容大小

标签: ios iphone swift


【解决方案1】:

如果您的情节提要中有AutoLayout,您可以这样做。您需要创建高度和宽度约束的出口。

@IBOutlet weak var height: NSLayoutConstraint!
@IBOutlet weak var width: NSLayoutConstraint!

现在您可以通过为其分配常量值来根据需要更改它

width.constant = 400
height.constant = 200

希望对你有帮助!!

【讨论】:

  • 一旦您将UITextView 添加为subView,则无法更新其布局
  • 仅供参考,您可以拨打setNeedsLayout,然后拨打layoutIfNeeded进行更新。
【解决方案2】:

好的,当我在 UITextView 中调用 licenseView.layoutIfNeeded() layoutSubviews() 时,似乎将 contentSize 重置为文本大小。我不知道它到底使用了什么逻辑

我可以通过基于 UITextView 编写自定义类并覆盖 layoutSubviews 方法来解决我的问题,但我解决了这个问题:

licenseView.contentInset.bottom = button.frame.size.height

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多