首页 > 解决方案 > 快速拆分uilabel中的字符串多行

问题描述

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

UIL标签文本 -

能力倾向测试与您的要求相关的英语技能。它使组织/机构能够评估所有四种英语技能——阅读、写作、听力和口语以及核心必修部分(语法和词汇),或仅测试一项技能,例如阅读。

拆分为字符串数组,每个换行符,即使屏幕尺寸的每个维度(无论是 iphone 还是 ipad )。

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

[“能力倾向测试与您的要求相关的英语技能。它使组织/机构”,“评估所有四种英语技能 - 阅读,写作,听力和口语以及核心”,“强制性组件(语法和词汇)或测试只有一项技能,例如阅读。”]

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

标签: arraysswiftstringsplituilabel

解决方案


您的方法可能很难,相反我建议您使用其他方法,例如使用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 = ""
        }
 }

推荐阅读