将UIPopoverController的高度更改为UITextView的高度

时间:2015-08-25 16:11:34

标签: ios swift

在我的应用程序中,需要一个显示完整描述的弹出框元素。

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

1 个答案:

答案 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
}

我希望这对你有所帮助。