arrays - 快速拆分uilabel中的字符串多行
问题描述
我想拆分我的动态 UILabel 文本,如下所示
UIL标签文本 -
能力倾向测试与您的要求相关的英语技能。它使组织/机构能够评估所有四种英语技能——阅读、写作、听力和口语以及核心必修部分(语法和词汇),或仅测试一项技能,例如阅读。
拆分为字符串数组,每个换行符,即使屏幕尺寸的每个维度(无论是 iphone 还是 ipad )。
我想要的结果是字符串数组 -
[“能力倾向测试与您的要求相关的英语技能。它使组织/机构”,“评估所有四种英语技能 - 阅读,写作,听力和口语以及核心”,“强制性组件(语法和词汇)或测试只有一项技能,例如阅读。”]
对于 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 = ""
}
}
推荐阅读
- flutter - 如何使用 Flutter 在 Slack 频道中发送消息?
- c# - 无法使用带有标识字段的 EF Core 3.0 将 NULL 插入 SQL 数据库
- .net - .net winforms 在顶部对话框中显示表单
- python - os.system() 中的引号匹配
- git - .gitignore 只跟踪目录中任意深度的一个文件
- flask - 代码未更改时文件上传时出现意外的 500 内部服务器错误
- json - 从外部 json 值获取更新而不刷新整页
- python - 如何将 Django 默认页面更改为您的设计?
- java - 如何处理flutter Java/Kotlin
- mysql - 在 Docker 启动时创建 MySql 表