iOS Swift UITextView 文字高度自适应

前言:

来自UI需求,弹框固定一个高度,里面的文字高度不固定,当文字较少的时候,不发生滚动,当文字较多的时候,内部可以滚动。

效果图:


文字高度自适应_A.gif

代码地址:

代码地址:https://gitee.com/yuency/Autolayout
示例代码类名 【TextViewAutoHeightController】

上代码!

TextViewAutoHeightController.swift

import UIKit

class TextViewAutoHeightController: UIViewController {
    
    lazy var scrollview: UIScrollView = {
        let scrollview = UIScrollView()
        scrollview.backgroundColor = UIColor.purple
        return scrollview
    }()
    
    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = UIColor.red
        return containerView
    }()
    
    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.backgroundColor = UIColor.yellow
        textView.isScrollEnabled = false
        textView.textContainerInset = UIEdgeInsets.zero
        textView.textContainer.lineFragmentPadding = 0
        textView.text = "UITextView 文字高度自适应: UIScrollView + UIView + UITextView组合, 滚动视图高度固定, 当UITextView文字较少, 不需滑动, 当文字较多, 可以滑动."
        textView.font = UIFont.systemFont(ofSize: 20)
        return textView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        view.addSubview(scrollview)
        scrollview.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(120)
            make.left.equalToSuperview().offset(100)
            make.right.equalToSuperview().offset(-100)
            make.height.equalTo(280)
        }
        
        scrollview.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.left.bottom.right.equalToSuperview()
        }
        
        containerView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("打印 TextView 初始高度: \(textView.frame.height) ")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.textView.resignFirstResponder()
    }
}

结语

为什么会有这么多的小门道。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 你说周文雄现在在干嘛呢?不知道。
    燕子_d9fb阅读 117评论 0 1
  • 随着社会诚信体系建设的深入,企业或个人有涉诉记录,可以说寸步难行,现在很多银行也有自己的大数据系统,这些系统抓取这...
    马洪强阅读 54评论 0 0
  • 稳商界促发展 民营企业是推动经济社会发展的...
    亲亲_ba80阅读 118评论 0 0
  • 从3月初就陆陆续续听到周边同事朋友家里有小朋友的遭了甲流,幸运的是家里两个小朋友一直无恙,也偶尔听他们讲班上有小朋...
    如月公子阅读 115评论 0 2
  • Sparks of Artificial General Intelligence: Early experime...
    数科每日阅读 862评论 0 2