要求:
- Platform: iOS8.0+
- Language: Swift3.1
- Editor: Xcode8.3+
實(shí)現(xiàn):
- xib布局
- 核心代碼
原理:當(dāng)文本輸入改變時(shí)秘案,計(jì)算出當(dāng)前輸入文本的行數(shù)策精,再相應(yīng)計(jì)算出view對應(yīng)的高度height,然后回調(diào)到父vc中更新當(dāng)前view的高度約束甥郑。
1.獲取輸入文本的rect
fileprivate var rectOfInputText: CGRect{
let size = CGSize(width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right, height: CGFloat.greatestFiniteMagnitude)
let rect = (textView.text as NSString).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font!], context: nil)
return rect
}
```
>2.根據(jù)font的lineHeight計(jì)算當(dāng)前輸入文本的行數(shù)
fileprivate var linesOfInputText: Int{
return Int(rectOfInputText.height / textView.font!.lineHeight)
}
>3.根據(jù)輸入的文本計(jì)算當(dāng)前view對應(yīng)的最大高度
fileprivate func updateSelfHeightLayout(){
let lines = linesOfInputText > maxiumLines ? maxiumLines : linesOfInputText
let height = CGFloat(lines)*textView.font!.lineHeight + textView.textContainerInset.bottom + textView.textContainerInset.top + layoutMargins.top + layoutMargins.bottom
// 回調(diào)
callback?(.needsUpdateLayoutOfHeight, height)
}
>4.UITextViewDelegate輸入改變時(shí)計(jì)算高度
extension InputView: UITextViewDelegate{
func textViewDidChange(_ textView: UITextView) {
updateSelfHeightLayout() //計(jì)算高度,回調(diào)更新
}
}
#####用法

@IBOutlet weak var input: InputView!
@IBOutlet weak var inputHeightCons: NSLayoutConstraint!
override func viewDidLoad()
{
super.viewDidLoad()
// 配置方法
input.configure(placeholder: "輸入評論", actionTitle: "回復(fù)")
{[unowned self]
(type, info) in
// 改變高度回調(diào)
if type == .needsUpdateLayoutOfHeight{
self.inputHeightCons.constant = info as! CGFloat
UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
}
#####注意
**這個(gè)Demo我主要講述了如何根據(jù)輸入的文本內(nèi)容孟害,動(dòng)態(tài)計(jì)算并更新輸入框的高度腕让,并沒有加入鍵盤彈出相關(guān)的事件處理。**
###github
https://github.com/BackWorld/AutoHeightInputView
> 如果對你有幫助悦昵,別忘了點(diǎn)個(gè)??哦肴茄。