我想使用属性字符串更改UILabel
中标签的默认宽度。我怎样才能做到这一点?我假设我应该添加属性NSMutableParagraphStyle
,但我不知道哪个属性负责标签长度。
我们以此代码为例:
let text = "test\ttest"
let attributedText = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
let textRange = NSRange(location: 0, length: text.length)
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange)
答案 0 :(得分:2)
根据Apple Developer Documentation,var tabStops: [NSTextTab]!
是一个NSTextTab
个对象数组,表示接收者的制表位。您可以按如下方式访问标签并更改其位置:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: newTabLength, options: [:])]
label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle])
答案 1 :(得分:2)
要通过NSMutableParagraphStyle
更改tabstops的长度,您必须创建一个新的NSTextTab
个实例数组并将其分配给tabStops
数组
let text = "test\ttest\ttest"
let attributedText = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
let tabInterval : CGFloat = 40.0
var tabs = [NSTextTab]()
for i in 1...10 { tabs.append(NSTextTab(textAlignment: .left, location: tabInterval * CGFloat(i))) }
paragraphStyle.tabStops = tabs
let textRange = NSRange(location: 0, length: text.count)
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange)
答案 2 :(得分:1)
您可以尝试将\ t替换为您想要的空格数
var text = "test\ttest"
text = text.replacingOccurrences(of: "\\t", with: " ")
let attributedText = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
let textRange = NSRange(location: 0, length: text.length)
attributedText.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: textRange)