You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift iOS无xib/Storyboard如何创建可复用的两行文本展示TextView组件

纯代码实现可复用两行展示TextView组件流程

1. 完善自定义TextView基础代码

首先补全类的初始化逻辑,同时支持纯代码和xib两种初始化方式,配置基础展示属性:

@IBDesignable public class HyperLinksTextView: UITextView {
    // 支持纯代码初始化
    override public init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }
    
    // 支持xib初始化
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    private func commonInit() {
        backgroundColor = .clear
        // 禁止编辑、禁止滚动,适配纯展示场景
        isEditable = false
        isScrollEnabled = false
        isSelectable = true // 需要支持链接点击就开启,不需要可设为false
        
        // 配置最大行数为2,超出内容尾部截断
        textContainer.maximumNumberOfLines = 2
        textContainer.lineBreakMode = .byTruncatingTail
        // 去除TextView默认内边距,也可按需求自定义数值
        textContainerInset = .zero
        textContainer.lineFragmentPadding = 0
        
        // 可选:配置链接样式,匹配类名的超链接需求
        linkTextAttributes = [
            .foregroundColor: UIColor.blue,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
    }
    
    // 对外暴露的内容配置方法,支持自定义字体、行间距等参数
    public func setTwoLineContent(firstLine: String,
                                 secondLine: String,
                                 font: UIFont = UIFont.systemFont(ofSize: 14),
                                 lineSpacing: CGFloat = 4,
                                 textColor: UIColor = .black) {
        let attributedStr = NSMutableAttributedString(string: "\(firstLine)\n\(secondLine)")
        // 配置文本段落样式
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineBreakMode = .byTruncatingTail
        
        attributedStr.addAttributes([
            .font: font,
            .foregroundColor: textColor,
            .paragraphStyle: paragraphStyle
        ], range: NSRange(location: 0, length: attributedStr.length))
        
        attributedText = attributedStr
    }
}

2. 纯代码调用示例

无需依赖xib/Storyboard,直接在业务页面初始化使用即可:

class DemoViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        // 初始化自定义TextView组件
        let twoLineTextView = HyperLinksTextView()
        twoLineTextView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(twoLineTextView)
        
        // 添加约束,仅需设置位置和宽度,高度会自动适配两行内容
        NSLayoutConstraint.activate([
            twoLineTextView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            twoLineTextView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            twoLineTextView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)
        ])
        
        // 传入两行展示内容
        twoLineTextView.setTwoLineContent(
            firstLine: "这是第一行展示的文本内容",
            secondLine: "这是第二行展示的文本内容,超出宽度会自动截断尾部",
            font: UIFont.systemFont(ofSize: 14),
            lineSpacing: 4,
            textColor: .darkText
        )
    }
}

3. 扩展说明

  • 如果需要支持超链接点击,只需要在setTwoLineContent方法中给指定文本范围额外添加.link属性即可
  • 组件默认关闭了内边距,有需求可以自行修改textContainerInset的数值调整内边距
  • 因为关闭了滚动功能,组件大小会自动适配文本内容,自动布局时不需要强制设置高度约束

内容的提问来源于stack exchange,提问作者iOSDuDe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:45:08