swift4.0 評論彈出鍵盤的封裝

demo地址:

https://github.com/weiman152/SwiftCustomInputView

很多應用都有評論功能,評論功能涉及到的問題主要就是兩個:
1.鍵盤彈出的高度
2.動態改變textview的高度

剩下的就是一些動畫了。

這里封裝的主要是這兩部分的實現,可以方便的調用,簡單使用如下:

 @IBAction func inputButtonAction(_ sender: UIButton) {
        
        let view = CustomInputView.instance(superView: self.view)
        view?.delegate = self
        
    }

實現效果:

111.gif
image.png
image.png
image.png
image.png

主要代碼:

//
//  CustomInputView.swift
//  CustomInputView
//
//  Created by iOS on 2018/5/24.
//  Copyright ? 2018年 weiman. All rights reserved.
//

import UIKit

protocol CustomInputViewDelegate: NSObjectProtocol {
    /// 發送
    func send(text: String)
}

class CustomInputView: UIView {
    
    weak var delegate: CustomInputViewDelegate?
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
    @IBOutlet weak var bottomViewBottom: NSLayoutConstraint!
    
    /// 最大限制字數,默認是100
    private var maxWords: Int = 300
    /// 在textview不滾動的情況下,允許輸入的最大行數,超過這個行數,就進行滾動
    private var maxRows: Int = 6
    private var oneLineHeight: CGFloat = 0
    private var origialHeight: CGFloat = 0
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
        setupLayout()
        setupNotification()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
        setupLayout()
        setupNotification()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    private func setup() {
        backgroundColor = UIColor(white: 0.5, alpha: 0.3)
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.hex("eeeeee").cgColor
        textView.layer.cornerRadius = 20
        textView.layer.masksToBounds = true
        
        textView.delegate = self
        textView.becomeFirstResponder()
        // 這句話讓光標不會因為圓角而被遮擋一塊
        textView.textContainerInset = UIEdgeInsets(top: 10, left: 5, bottom: 5, right: 5)
        
        origialHeight = bottomViewHeight.constant
    }
    
    private func setupLayout() {
        
    }
    
    /// 通知
    private func setupNotification() {
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillChange),
            name: .UIKeyboardWillChangeFrame,
            object: nil
        )
    }
    
}

/// 公有方法
extension CustomInputView {
    
    /// 初始化
    class func instance(superView: UIView) -> CustomInputView? {
        let view = Bundle.main.loadNibNamed("CustomInputView", owner: nil, options: nil)?.last
        guard let customView = view as? CustomInputView else {
            return nil
        }
        superView.addSubview(customView)
        customView.frame = superView.bounds
        return customView
    }
    
    /// 消失
    func dismiss() {
       removeFromSuperview()
    }
    
    /// 設置背景顏色和透明度
    func set(backgroundColor: String, alpha: CGFloat = 1.0) {
        self.backgroundColor = .hex(backgroundColor, alpha: alpha)
    }
    
    /// 最大字數限制
    func set(max: Int) {
       self.maxWords = max
    }
    
    /// 在textview不滾動的情況下,允許輸入的最大行數,超過這個行數,就進行滾動
    /// 注意,不是最多輸入的行數
    func set(maxRows: Int) {
        self.maxRows = maxRows
    }
    
}

/// 私有方法
extension CustomInputView {
    
    @IBAction func sendButtonAction(_ sender: UIButton) {
        delegate?.send(text: textView.text)
    }
    
    @objc private func keyboardWillChange(_ notify: Notification) {
        guard let userInfo = notify.userInfo else {
            return
        }
        guard
            let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as?TimeInterval,
            let curveRaw = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int,
            let curve = UIViewAnimationCurve(rawValue: curveRaw),
            let endRect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
                return
        }
        
        handleKeyBoardFrame(duration: duration, curve: curve, endRect: endRect)
    }
    
    private func handleKeyBoardFrame(duration: TimeInterval,
                                     curve: UIViewAnimationCurve,
                                     endRect: CGRect) {
        // 注意:endRect在第三方鍵盤上獲取的時候會先后出現兩個高度,所以設置高度的時候,不要把下面這句話放在動畫里面執行,不然的話,第三方鍵盤會抖一下
        self.bottomViewBottom.constant = endRect.height
        UIView.animate(withDuration: duration, animations: { [weak self] in
            self?.layoutIfNeeded()
        }) { (_) in
            
        }
    }
    
    private func handleBottomHeight(currentHeight: CGFloat, maxHeight: CGFloat) {
        // 一行的高度
        if oneLineHeight == 0 {
            oneLineHeight = currentHeight
        }
        if currentHeight <= oneLineHeight {
            bottomViewHeight.constant = origialHeight
        } else {
            if CGFloat(currentHeight) < maxHeight {
                bottomViewHeight.constant = CGFloat(currentHeight)
            } else {
                bottomViewHeight.constant = maxHeight
            }
        }
        
        UIView.animate(withDuration: 0.2) {
            self.layoutIfNeeded()
        }
    }
    
    private func handleTextHeight(textView: UITextView) {
        // 一行的高度(居然還有這種方法,漲知識)
        guard let lineHeight = textView.font?.lineHeight else {
            return
        }
        
        // ceilf:向上取整
        let textMaxHeight = ceilf(Float(lineHeight) * Float(maxRows))
        // 最大高度,別忘了上下間距
        let maxHeight: CGFloat = CGFloat(textMaxHeight) + extraSize().paddingTop + extraSize().paddingBottom + extraSize().marginTop + extraSize().marginBottom
        let size = textView.sizeThatFits(CGSize(width: textView.bounds.width, height: CGFloat(MAXFLOAT)))
        let currentHeight = CGFloat(ceilf(Float(size.height))) + extraSize().paddingTop + extraSize().paddingBottom + extraSize().marginTop + extraSize().marginBottom
        
        handleBottomHeight(currentHeight: currentHeight, maxHeight: maxHeight)
        
    }
    
    private func extraSize() -> (paddingTop: CGFloat, paddingBottom: CGFloat, marginTop: CGFloat, marginBottom: CGFloat) {
        let textTop: CGFloat = textView.textContainerInset.top
        let textBottom: CGFloat = textView.textContainerInset.bottom
        let textViewTop: CGFloat = 10
        let textViewBottom: CGFloat = 10
        
        return (textTop,textBottom,textViewTop,textViewBottom)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss()
    }
}

/// 代理方法
extension CustomInputView: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        // 判斷輸入是否超出規定長度
        if let text = textView.text, text.count >= maxWords {
            let result = text.prefix(maxWords)
            textView.text = String(result)
            return
        }
        
        if textView.text.count > 0 {
            sendButton.isSelected = true
        } else {
            sendButton.isSelected = false
        }
        
        // 計算當前textview內容的高度,動態改變textview以及父view的高度
        handleTextHeight(textView: textView)
    }
}

/// UIColor的擴展
extension UIColor {
    
    static func hex(_ string: String, alpha: CGFloat = 1.0) -> UIColor {
        let scanner = Scanner(string: string)
        scanner.scanLocation = 0
        var rgbValue: UInt64 = 0
        scanner.scanHexInt64(&rgbValue)
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0x00ff00) >> 8
        let b = (rgbValue & 0x0000ff)
        if #available(iOS 10.0, *) {
            return UIColor(
                displayP3Red: CGFloat(r) / 0xff,
                green: CGFloat(g) / 0xff,
                blue: CGFloat(b) / 0xff,
                alpha: alpha
            )
        } else {
            return UIColor(
                red: CGFloat(r) / 0xff,
                green: CGFloat(g) / 0xff,
                blue: CGFloat(b) / 0xff,
                alpha: alpha
            )
        }
    }
}


是不是挺簡單的?明白了不?
備注:有些屬性是在xib上設置的,需要的話,可以下載demo。

祝開心。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,200評論 4 61
  • 看多了瑪麗蘇的小白文,該看點現實生活中的愛情故事來洗洗腦子了。不是所以的王子都騎著白馬來...... 烈途 by:...
    W君的日常分享閱讀 6,414評論 0 3
  • 背景 在提交表單的時候,通常有一種情況是新增加一條記錄。當新增成功的時候,跳到添加成功的界面,如果用戶點擊了瀏覽器...
    七弦桐語閱讀 993評論 0 2
  • CSS中由一種基礎設計模式叫盒模型,盒模型定義了Web頁面中的元素如何來解析.CSS中每一個元素都是一個盒模型,包...
    Mandy_jin閱讀 282評論 0 0