避免在多行UILabel中使用单个字符换行

时间:2019-06-18 13:33:59

标签: ios swift uilabel

我有一个(动态尺寸的)UILabel,其numberOfLines = 2。

根据来自BE的文本,文本是否被正确包装。

关于如何防止将(长)单词分成两行并且在新行中仅包含一个字符的问题,有人有技巧吗?

当前行为:

Thisisalongwor
d

想要的行为:

Thisisalong
word

基本上:我想设置每行的最小字符数(将项目从第一行包装到第二行时)。

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一种方法...

使用CoreText函数从标签获取换行数组。如果最后一行具有 至少1 个字符,但 少于4个 个字符,则全文为< 大于4个 个字符,请在文本末尾插入一个换行4个字符并更新标签。

因此,基于默认的UILabel-17点系统字体-固定宽度为123-pts,并且将换行设置为Character Wrap,它看起来像这样:

enter image description here

运行fixLabelWrap(...)函数后,它看起来像这样:

enter image description here

示例代码:

class CharWrapViewController: UIViewController {

    @IBOutlet var theLabel: UILabel!

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        fixLabelWrap(theLabel)
    }

    func fixLabelWrap(_ label: UILabel) -> Void {

        // get the text from the label
        var text = theLabel.text ?? ""

        // get an array of the char-wrapped text
        let lines = getLinesArrayOfString(in: theLabel)

        // if it is more than one line
        if lines.count > 1 {
            // get the last line
            if let lastLine = lines.last {
                // if the last line has at least 1 char, is less than 4 chars, and
                // the full text is greater than 4 chars
                if lastLine.count > 0 && lastLine.count < 4 && text.count > 4 {
                    // insert a line-feed 4 chars before the end
                    text.insert("\n", at: text.index(text.endIndex, offsetBy: -4))
                    // update the text in the label
                    theLabel.text = text
                }
            }
        }

    }

    func getLinesArrayOfString(in label: UILabel) -> [String] {

        /// An empty string's array
        var linesArray = [String]()

        guard let text = label.text, let attStr = label.attributedText else { return linesArray }

        let rect = label.frame

        let frameSetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
        let path: CGMutablePath = CGMutablePath()
        path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000), transform: .identity)

        let frame: CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
        guard let lines = CTFrameGetLines(frame) as? [Any] else {return linesArray}

        for line in lines {
            let lineRef = line as! CTLine
            let lineRange: CFRange = CTLineGetStringRange(lineRef)
            let range = NSRange(location: lineRange.location, length: lineRange.length)
            let lineString: String = (text as NSString).substring(with: range)
            linesArray.append(lineString)
        }

        return linesArray
    }

}

注意:getLinesArrayOfString(...)函数是对该帖子的稍微修改的版本:https://stackoverflow.com/a/14413484/6257435