在我的应用程序中,需要一个显示完整描述的弹出框元素。
UITextView
中有一个正常UIViewController
,显示说明的前4行。现在,当用户单击该描述时,必须显示完整描述。这将通过最近为iPhone推出的popover控件来完成。
目前一切正常,除了我希望弹出窗口的高度正好是UITextView
DescriptionPopupViewController
中字符串的高度。这样,如果描述更长,它将自动使弹出更高。
当用户点击UITextView
:
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if textView == descriptionTextView {
let sb = UIStoryboard(name: "Main-alternative", bundle: nil)
let popoverController = sb.instantiateViewControllerWithIdentifier("descriptionControllerID") as! DescriptionPopupViewController
popoverController.modalPresentationStyle = UIModalPresentationStyle.Popover
popoverController.popoverPresentationController?.delegate = popoverController;
popoverController.popoverPresentationController?.sourceView = descriptionTextView
popoverController.popoverPresentationController?.sourceRect = descriptionTextView.frame
popoverController.descriptionText = currentObject?["description"] as! String
if let frameHeight = popoverController.textView?.frame.height {
popoverController.preferredContentSize = CGSizeMake(fixedWidth, frameHeight)
}
self.presentViewController(popoverController, animated: true, completion: nil)
}
return false
}
因此preferredContentSize
应该获得UITextView
中所包含的DescriptionPopupViewController
的高度。然而,当我尝试做这样的事情时,它不会工作:
我认为因为frameHeight是nil
答案 0 :(得分:0)
创建UIViewController
时,其视图层次结构可能不会(因此所有子视图,属性仍为nil
),出于优化原因,可能无法加载。您需要访问控制器view
强制它加载其视图层次结构。因此,您需要更新以下代码:
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if textView == descriptionTextView {
let sb = UIStoryboard(name: "Main-alternative", bundle: nil)
let popoverController = sb.instantiateViewControllerWithIdentifier("descriptionControllerID") as! DescriptionPopupViewController
popoverController.modalPresentationStyle = UIModalPresentationStyle.Popover
popoverController.popoverPresentationController?.delegate = popoverController;
popoverController.popoverPresentationController?.sourceView = descriptionTextView
popoverController.popoverPresentationController?.sourceRect = descriptionTextView.frame
// forces to load its view hierarchy
var view = popoverController.view
popoverController.descriptionText = currentObject?["description"] as! String
if let frameHeight = popoverController.textView?.frame.height {
popoverController.preferredContentSize = CGSizeMake(fixedWidth, frameHeight)
}
self.presentViewController(popoverController, animated: true, completion: nil)
}
return false
}
我希望这对你有所帮助。