Swift textview scrollRangeToVisible在textFieldDidBeginEditing中不起作用

时间:2016-12-13 13:59:33

标签: swift autolayout textview constraints scrollview

我正在建立一个聊天,当我输入一条消息并按下发送按钮时,textview会定位在底部,就像我想要的那样。但是,当我关闭键盘并单击以键入另一条消息时,textview位于顶部,我想在底部。我尝试将scrollRangeToVisible放在textFieldDidBeginEditing中但不起作用。

按照代码:

@IBAction func sendMessage(_ sender: AnyObject) {
    let date = NSDate()
    let calendar = NSCalendar.current
    let components = calendar.dateComponents([.hour, .minute], from: date as Date)
    let complement = "Sender (" + String(describing: components.hour!) + ":" + String(describing: components.minute!) + ") "
    self.chatTextView.text = (self.chatTextView.text)! + complement + self.textMessage.text! + "\n\n"
    self.textMessage.text = ""
    chatTextView.resignFirstResponder()
    let stringLength:Int = self.chatTextView.text.characters.count
    self.chatTextView.scrollRangeToVisible(NSMakeRange(stringLength-1, 0))
}

 func textFieldDidBeginEditing(_ textField: UITextField) {
    scrollView.setContentOffset(CGPoint(x:0,y:250),animated: true)
    heightChatTextConstraint.constant = heightChatTextConstraint.constant - 250
    let stringLength:Int = self.chatTextView.text.characters.count
    self.chatTextView.scrollRangeToVisible(NSMakeRange(stringLength-1, 0))
}

func textFieldDidEndEditing(_ textField: UITextField) {
    scrollView.setContentOffset(CGPoint(x:0,y:0),animated: true)
    heightChatTextConstraint.constant = heightChatTextConstraint.constant + 250
}

按照图像正常工作(当我在不关闭键盘的情况下输入一条接一条消息时):

enter image description here

关注图片无法正常工作(在我关闭键盘并点击键入新消息后,textview不会显示在底部):

enter image description here

0 个答案:

没有答案