0

我正在做一個筆記應用程序。 我節省歸因文本 On DetailVC 和我在UITableViewCell標籤中顯示預覽。swift - 如何刪除NSAttributedString中的空白(空)行?

在標籤我有這樣

The Bold Title 

my Text 

文字,我想改變這種像

The Bold Title 
my Text 

我發現字符串的解決方案

let regex = try! NSRegularExpression(pattern: "\n+", options: []) 
let newString = regex.stringByReplacingMatches(in: MyString, options: [], range: NSRange(location: 0, length: MyString.characters.count), withTemplate: "\n") 

但我怎麼能在NSAttirbutedStr ing

請幫忙!

回答

1

您可以製作一個NSMutableAttributedString這是一個歸屬字符串,允許對其內容進行變形,然後使用它的屬性mutableString

如果您已有NSAttributedString,則可以使用mutableCopy()或查看possible initializers of NSMutableAttributedString

let str = NSMutableAttributedString(string: "Hardcore\n\nHenry") 
str.mutableString.replaceOccurrences(of: "\n\n", with: "\n", options: [], range: NSMakeRange(0, str.length)) 
print(str) 
+0

非常感謝!但它沒有任何屬性!我怎樣才能解決這個問題? – Daniel

+0

您可以根據需要添加屬性。例如你可以使用'str.addAttribute(NSForegroundColorAttributeName,value:UIColor.red,range:NSMakeRange(0,8))'(這是swift3,swift2.x使用'UIColor.redColor()') 'Hardcore'紅色。它不會顯示在'print()'中。你必須使用'UILabel'來看看它會是什麼樣子。 – Majster

+0

謝謝......但我的問題是替換屬性文本**保留**它是自己的屬性。 (我用UILabel ...) – Daniel