美文网首页
iOS Swift UITextView 文字高度自适应

iOS Swift UITextView 文字高度自适应

作者: Yuency | 来源:发表于2023-03-26 11:14 被阅读0次

前言:

来自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()
    }
}

结语

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

相关文章

网友评论

      本文标题:iOS Swift UITextView 文字高度自适应

      本文链接:https://www.haomeiwen.com/subject/ohpordtx.html