在 uilabel 中拆分字符串多行 swift

Split string in uilabel multiple lines swift

我想拆分我的动态 UILabel 文本,如下所示,例如

UILabel 文本 -

Aptitude tests English skills relevant to your requirements. It enables an organisation / institution to assess all four English skills – reading, writing, listening and speaking together with the core mandatory component (grammar and vocabulary) or test just one skill, e.g. reading.

拆分成字符串数组,每行换行符与屏幕大小的每个维度相等,无论是 iphone 还是 ipad 。

我想要的结果是字符串数组 -

["Aptitude tests English skills relevant to your requirements. It enables an organisation / institution","to assess all four English skills – reading, writing, listening and speaking together with the core ","mandatory component (grammar and vocabulary) or test just one skill, e.g. reading."]

对于 UILabel 中的每个换行符,无论动态屏幕大小如何,我都需要拆分字符串

您的方法可能很难,我建议您使用其他方法,例如 sizeWithAttributes

extension String {

func widthOfString(usingFont font: UIFont) -> CGFloat {
    let fontAttributes = [NSAttributedString.Key.font: font]
    let size = self.size(withAttributes: fontAttributes)
    return size.width
}

func heightOfString(usingFont font: UIFont) -> CGFloat {
    let fontAttributes = [NSAttributedString.Key.font: font]
    let size = self.size(withAttributes: fontAttributes)
    return size.height
}

func sizeOfString(usingFont font: UIFont) -> CGSize {
    let fontAttributes = [NSAttributedString.Key.font: font]
    return self.size(withAttributes: fontAttributes)
    }
}

假设您知道标签中的宽度和字体大小,您可以使用如下逻辑:

    let inputText = "Aptitude tests English skills relevant to your requirements. It enables an organisation / institution to assess all four English skills – reading, writing, listening and speaking together with the core mandatory component (grammar and vocabulary) or test just one skill, e.g. reading."
    let labelWidth = UIScreen.main.bounds.width
    var resultArray:[String] = []
    var readerString = ""
    for i in 0 ..< inputText.count
    {

        readerString += inputText[i]
        //Check if overflowing boundries and wrapping for new line
        if readerString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) >= labelWidth {
            resultArray.append(readerString)
            readerString = ""
        }
 }