ios - 设置内容高度后无法更新 UITextView 大小

标签 ios iphone swift

我需要的是在首次启动应用程序时显示许可协议(protocol)。简单的 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 - 当我向下滚动时,我看到该按钮位于可滚动区域之外。我错过了什么?

最佳答案

如果 Storyboard中有AutoLayout,您就可以做到这一点。您需要创建高度和宽度约束的导出。

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

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

width.constant = 400
height.constant = 200

希望这可以帮助你!!

关于ios - 设置内容高度后无法更新 UITextView 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265598/

相关文章:

iphone - Windows 记事本不支持换行符 '\n'

Swift 3 init - 意外错误

ios - 为什么我的应用程序图标没有出现在 iPhone 的某个系统功能中?

ios - 解开可选值错误 - 检查应用内购买的收据响应

ios - Swift 将数据转换为 UnsafeMutablePointer<Int8>

ios - 使用 facebook iOS SDK 登录后台账户

ios - 如何为 iOS 中的每个文本字段创建可访问和可编辑的动态文本字段

swift - 在 SwiftUI 中创建 BaseView 类

Swift 2.2 undefined symbol 阻止构建

ios - RPScreenRecorder 在奇怪的情况下不录制麦克风