简体   繁体   中英

TextView does not format text properly the first time, but does the second time

I am working on a messaging app and am trying to make a UITextView that adjusts based on input. When I add text to the view and it indents, it does not format properly (shown in image 1 below and represented by the third function of my code). Strangely, when I dismiss and reopen the keyboard, it formats as desired (this can be attributed to the first function of my code and is shown in image 2). Any help? Also, to clarify, the "..." in my code is necessary for an unrelated step I am going to carry out later (though I left it in as it may affect the code). My code:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.textView.frame.origin.y -= keyboardSize.height
        self.send.frame.origin.y -= keyboardSize.height
        let number = textView.contentSize.height / textView.font!.lineHeight
        textView.frame.size.height = CGFloat(42 + Double((Int(number) - 1))*20.3)
        textView.frame.origin.y -= CGFloat(Double((Int(number) - 1))*20.3)
        textView.text = "................................................................................."
        textView.text = textMessage
        textView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
        textView.alpha = 1
        send.backgroundColor = UIColor(red: 0.08627, green: 0.5373, blue: 1, alpha: 1)
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    self.textView.frame.origin.y = 619
    self.send.frame.origin.y = 623
    textView.frame.size.height = 42
    textMessage = textView.text
}

func textViewDidChange(_ textView: UITextView) {
    let number = textView.contentSize.height / textView.font!.lineHeight
    print(textView.font!.lineHeight)
    new = Int(number)
    if new != old {
        textView.frame.size.height = CGFloat(42 + Double((Int(number) - 1))*20.3)
        textView.frame.origin.y -= CGFloat(20.3)
    }
    old = new
}

图片2 图片1

you need to provide more information about it but if you want to pre-charge any type of information or functions before the screen start. you could use

override func viewWillAppear(_ animated: Bool) {
//add want ever you want to do
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM