首页 > 解决方案 > 将长文本放入 UILabel 中的多行

问题描述

在我的 UI 中有一个UILabel,并且在运行时将文本设置为它。如果文本太长,它应该显示为两行。

UILabel 的代码如下。

    lazy var disLabel:UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .left
        label.font = Fonts.fontForType(fontType: .AktivGroteskRegular, fontSize: 15.0)
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.backgroundColor = UIColor.red
        label.text = "Hello world. How are you.  XaXaXa
        return label
    }()

然后我设置约束如下。

        label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true
        label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true

输出如下。

在此处输入图像描述

这里有足够的空间来写“你”这个词。但它已经走到了第二行。无论文本是什么,第一行总是有很多空间。

如何解决这个问题。

标签: iosswiftuilabel

解决方案


推荐阅读