我很难从 UITextView
获得.Text值以转换为字符串,因此我可以将其索引并吐在" n"上。如果我通过引号中的字符串有效,但是如果我使用.TEXT值,则拒绝在" n"
这是我的功能:
func formatLabel(string: String, title_color: UIColor, title_font_size: CGFloat, title_font_weight: UIFont.Weight, subtitle_color: UIColor, subtitle_font_size: CGFloat) -> NSMutableAttributedString {
//getting the range to separate the button title strings
let index = string.index(of: "n") ?? string.endIndex
let substring1 = String(string[..<index])
let substring2 = String(string[index...])
print("string:", string)
print("index: ",index)
print("line 1", substring1)
print("line 2", substring2)
}
这是我的ViewController代码:
@IBAction func btnUpdate(_ sender: Any) {
txtOutput.attributedText = formatLabel(string: txtInput.text!, title_color: UIColor.gray, title_font_size: 17, title_font_weight: UIFont.Weight.bold, subtitle_color: UIColor.lightGray, subtitle_font_size: 13)
txtOutput2.attributedText = formatLabel(string: "TitlenSub Title", title_color: UIColor.gray, title_font_size: 17, title_font_weight: UIFont.Weight.bold, subtitle_color: UIColor.lightGray, subtitle_font_size: 13)
}
这是打印输出:
string: TitlenSub Title
index: Index(_compoundOffset: 64, _cache:
Swift.String.Index._Cache.utf16)
line 1 TitlenSub Title
line 2
string: Title
Sub Title
index: Index(_compoundOffset: 20, _cache: Swift.String.Index._Cache.character(1))
line 1 Title
line 2
Sub Title
因此,当使用uItextView控件时,我无法获得索引(" n")的索引,但是当我使用文字文本时就可以了。我所能确定的是Swift 4中,必须做一些时髦的事情来处理复合声。记录在很悠久的情况下,因此无法弄清楚如何解决我的问题并让控制文本以字符串的形式行为。任何帮助将不胜感激。
UITextView
组件不会自动将用户键入的" n"转换为返回字符。
您可以使用:
txtOutput.attributedText = formatLabel(string: txtInput.text!.replacingOccurrences(of: "\n", with: "n"), title_color: UIColor.gray, title_font_size: 17, title_font_weight: UIFont.Weight.bold, subtitle_color: UIColor.lightGray, subtitle_font_size: 13)
这将用适当的返回字符替换" n"。
P.S。但是,您不应该强制 txtInput.text
值。