根据 UITextView swift 的大小向上移动子视图



我有一个UITextView,当用户键入多行文本时,它会改变高度。 我的问题是,当用户键入足够的行时,UITextView会被位于文本视图上方的UITableView所掩盖。 当文本视图的高度增加时,有没有办法以编程方式向上移动表视图?

这是更改文本视图高度的原因,该视图位于textViewDidChange函数中:

if (self.contentSize.height > self.frame.height && self.contentSize.height < 166){
        self.frame.origin.y -= (self.contentSize.height - self.frame.height)
        self.frame.size = self.contentSize
    }else if (self.contentSize.height < self.frame.height){
        self.frame.origin.y += self.frame.height - self.contentSize.height
        self.frame.size = self.contentSize
    }

如果你使用故事板,你可以很容易地使用NSLayoutConstraint来做到这一点,你也可以在代码中做到这一点,但在stroyboard中会容易得多。如果文本视图位于底部,则可以按住 Ctrl 键将其拖动到表视图并使用垂直间距。 对于 iMessage 样式文本视图,请使用将文本视图固定到具有布局约束的 VC 视图的底部,并将其顶部固定到表视图的底部。 您必须在VC中注册UIKeyBoardWillHide和UIKeyboardWillShow。 然后实现一个类似于底部的方法。 您可以在 viewDidAppear 中添加观察点,并在 viewWillDisappear 中移除它们。 以下方法中的高度变量是指我在文本视图的高度上设置的约束,底部约束是情节提要中设置的文本视图的底部约束的 IBOutlet。

' func keyboardToggle(notification: NSNotification) {

    let info:AnyObject = notification.userInfo!
    let keyboardHeight = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().height
    let duration = info[UIKeyboardAnimationDurationUserInfoKey] as Double
    var height:CGFloat!
    var botConst: CGFloat!

    switch notification.name {
    case UIKeyboardWillShowNotification:
        height = textView.contentSize.height
        botConst = keyboardHeight
    case UIKeyboardWillHideNotification:
        height = 40.0
        botConst = 0.0
        characterCountLabel.hidden = true
                bottomConstraint.constant = botConst
    view.layoutIfNeeded()
    delegate.view.layoutIfNeeded()
    UIView.animateWithDuration(duration, animations: { () -> Void in
        self.view.layoutIfNeeded()
        self.delegate.view.layoutIfNeeded()
    })

'

我最终采取了与上述答案略有不同的方法。 我使用 NSNotificationCenter 发送了文本已输入文本视图的通知,然后更新了文本视图的大小并更新了表视图的 y 坐标。

这是更新我的文本视图和表视图位置的函数:

func keyPressed(sender: NSNotification) {
    if let text = textView{
        if let messages = messageViews{
            if (text.contentSize.height > text.frame.height){
                messages.frame.origin.y -= (text.contentSize.height - text.frame.height)
                text.frame.origin.y -= (text.contentSize.height - text.frame.height)
                text.frame.size = text.contentSize
            }else if(text.contentSize.height < text.frame.height){
                messages.frame.origin.y += (text.frame.height - text.contentSize.height)
                text.frame.origin.y += (text.frame.height - text.contentSize.height)
                text.frame.size = text.contentSize
            }
        }
    }
}

最新更新