如何使用10行限制textview文本高度,然后保留文本以在Swift3中滚动

时间:2017-07-06 11:34:37

标签: ios swift swift3 uitextview

这里我设计了一个textview,它将随键盘向上移动并根据文本调整其高度,在textview中没有textview的滚动,现在我需要textview应该限制10行然后想要滚动。

以下是我的代码:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate{

    @IBOutlet weak var msgTextViewheightConstraint: NSLayoutConstraint!
    @IBOutlet weak var msgTextView: UITextView!
    @IBOutlet weak var textViewBottomLayoutContraint: NSLayoutConstraint!

    var activeTextView: UITextView?

    override func viewDidLoad() {
        super.viewDidLoad()

        msgTextView.layer.cornerRadius = 5
        msgTextView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
        msgTextView.layer.borderWidth = 0.5
        msgTextView.clipsToBounds = true
        self.setupTextView()
        self.registerForKeyboardNotifications()
    }

    func registerForKeyboardNotifications(){
        //Adding notifies on keyboard appearing
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func deregisterFromKeyboardNotifications(){
        //Removing notifies on keyboard appearing
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = keyboardSize.size.height + 10

        }
    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = 10

        }
    }

    func textViewDidBeginEditing(_ textView: UITextView) {

        activeTextView = textView

    }
    func textViewDidEndEditing(_ textView: UITextView) {
        activeTextView = nil

    }
    private func textViewShouldReturn(_ textView: UITextView) -> Bool {
        textView.resignFirstResponder()
        return true
    }

    func setupTextView() {
        if let txtView = msgTextView {

            txtView.scrollsToTop = true
            txtView.isScrollEnabled = true

            txtView.addObserver(self, forKeyPath: "contentSize", options:[ NSKeyValueObservingOptions.old , NSKeyValueObservingOptions.new], context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let changeDict = change, let constraint = msgTextViewheightConstraint, let view = self.msgTextView {
            if object as? NSObject == self.msgTextView && keyPath == "contentSize" {
                if let oldContentSize = (changeDict[NSKeyValueChangeKey.oldKey] as AnyObject).cgSizeValue,
                    let newContentSize = (changeDict[NSKeyValueChangeKey.newKey] as AnyObject).cgSizeValue {

                    let dy = newContentSize.height - oldContentSize.height
                    constraint.constant = constraint.constant + dy;
                    self.view.layoutIfNeeded()
                    let contentOffsetToShowLastLine = CGPoint(x: 0.0, y: view.contentSize.height - view.bounds.height)
                    view.contentOffset = contentOffsetToShowLastLine
                }
            }
        }
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        return true
    }

}

请帮助我理解这个概念。

1 个答案:

答案 0 :(得分:0)

您可以通过将textView内容的高度除以textView的字体高度来获得文字行数:< / p>

let numberOfLines = textView.contentSize.height/(textView.font?.lineHeight)!

然后,您可以通过将textView.contentSize除以其包含的行数来获取每行的大小:

let lineHeight = textView.contentSize.height / numberOfLines

然后,在viewDidAppear方法中,您可以将textView的高度限制设置为lineHeight次10:

NSLayoutConstraint.activate([
    textView.heightAnchor.constraint(lessThanOrEqualToConstant: lineHeight * 10)
])

如果您这样做,请确保没有在故事板中设置高度限制。