ios swift UITextView高度自適應(yīng)

在ios開(kāi)發(fā)中,用到多行輸入時(shí)一般都會(huì)用到UITextView。常見(jiàn)的比如說(shuō)聊天輸入框,評(píng)論輸入框等,當(dāng)用戶輸入多內(nèi)容時(shí),我們希望高度能根據(jù)用戶輸入的內(nèi)容擴(kuò)大而擴(kuò)大。其實(shí)實(shí)現(xiàn)這個(gè)功能也不是很難,只需要自定義一個(gè)類并繼承UITextView,然后實(shí)現(xiàn)其代理UITextViewDeletage,重寫textViewDidChange,只需要在這個(gè)方法中進(jìn)行處理即可。下面開(kāi)始擼代碼:

1.先創(chuàng)建一個(gè)類:MyTextView

class MyTextView: UITextView,UITextViewDelegate {

? ? var maxHeight:CGFloat=60//定義最大高度

? ? override init(frame:CGRect, textContainer:NSTextContainer?) {

? ? ? ? super.init(frame: frame, textContainer: textContainer)

? ? ? ? //textview的一些設(shè)置

? ? ? ? self.delegate=self

? ? ? ? self.layer.borderColor = UIColor.lightGray.cgColor

? ? ? ? self.layer.borderWidth=0.5

? ? ? ? self.layer.cornerRadius=5

? ? ? ? self.layer.masksToBounds=true

? ? }


? ? required init?(coder aDecoder:NSCoder) {

? ? ? ? fatalError("init(coder:) has not been implemented")

? ? }

? ? func? textViewDidChange(_textView:UITextView) {

? ? ? ? //獲取frame值

? ? ? ? letframe = textView.frame

? ? ? ? //定義一個(gè)constrainSize值用于計(jì)算textview的高度

? ? ? ? let constrainSize=CGSize(width:frame.size.width,height:CGFloat(MAXFLOAT))

? ? ? ? //獲取textview的真實(shí)高度

? ? ? ? var size = textView.sizeThatFits(constrainSize)

? ? ? ? //如果textview的高度大于最大高度高度就為最大高度并可以滾動(dòng),否則不能滾動(dòng)

? ? ? ? if size.height>=maxHeight{

? ? ? ? ? ? size.height=maxHeight

? ? ? ? ? ? textView.isScrollEnabled=true

? ? ? ? }else{

? ? ? ? ? ? textView.isScrollEnabled=false

? ? ? ? }

? ? ? ? //重新設(shè)置textview的高度

? ? ? ? textView.frame.size.height=size.height

? ? }

}

2.開(kāi)始測(cè)試:

class? ViewController:UIViewController{

? ? override? func? viewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? //測(cè)試自定義的TextView

? ? ? ? lettextview =MyTextView(frame:CGRect(x:20,y:100,width:200,height:30))

? ? ? ? self.view.addSubview(textview)

? ? }

}

3.運(yùn)行結(jié)果:



總結(jié):UITextView高度自適應(yīng)的實(shí)現(xiàn)就到這里了,如果有什么問(wèn)題歡迎評(píng)論、留言,謝謝!

demo下載地址:MyTextViewDemo

博客園地址:猿哥愛(ài)碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容