2017-04-22 85 views
0

我想用部分粗體的字符串設置標籤的文本。我想要大膽的話都以同一封信開頭,說「〜」。以字母開頭的粗體字

例如,我可以有字符串,「這〜字是勇敢的,所以是〜這個」

然後標籤的文本將包含字符串「是勇敢的,所以是「。

有誰知道是否有可能做出這樣的功能?我試過如下:

func makeStringBoldForLabel(str: String) { 
    var finalStr = "" 
    let words = str.components(separatedBy: " ") 
    for var word in words { 
     if word.characters.first == "~" { 
      var att = [NSFontAttributeName : boldFont] 
      let realWord = word.substring(from: word.startIndex) 
      finalStr = finalStr + NSMutableAttributedString(string:realWord, attributes:att) 
     } else { 
      finalStr = finalStr + word 
     } 
    } 
} 

,但得到的錯誤:

Binary operator '+' cannot be applied to operands of type 'String' and 'NSMutableAttributedString'

回答

0

容易解決的問題。

使用:

func makeStringBoldForLabel(str: String) { 
    let finalStr = NSMutableAttributedString(string: "") 
    let words = str.components(separatedBy: " ") 
    for var word in words { 
     if word.characters.first == "~" { 
      var att = [NSFontAttributeName : boldFont] 
      let realWord = word.substring(from: word.startIndex) 
      finalStr.append(NSMutableAttributedString(string:realWord, attributes:att)) 
     } else { 
      finalStr.append(NSMutableAttributedString(string: word)) 
     } 
    } 
} 
+0

就行發生錯誤「finalStr = finalStr + NSMutableAttributedString(字符串:realWord,屬性:ATT)」,如果我投「finalStr」作爲nsmutableattributedstring我得到一個錯誤,說我不能添加2個nsmutableattributedstrings –

+0

啊。我更新了答案。這應該可以解決你的問題。 – Finn

+0

問題是你不能在NSMutableAttributedStrings上使用'+'。相反,你必須使用.append()。 – Finn

0

該錯誤信息是明確的,你不能連接StringNSAttributedString+運營商。

您在查找API enumerateSubstrings:options。它逐個枚舉字符串,通過.byWords選項。不幸的是,代字號(~)不被識別爲字詞分隔符,所以我們必須檢查一個字是否有前面的代字號。然後更改特定範圍的字體屬性。

let string = "This ~word is bold, and so is ~this" 

let attributedString = NSMutableAttributedString(string: string, attributes:[NSFontAttributeName : NSFont.systemFont(ofSize: 14.0)]) 
let boldAttribute = NSFont.boldSystemFont(ofSize: 14.0) 

string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) { (substring, substringRange, enclosingRange, stop) ->() in 
    if substring == nil { return } 
    if substringRange.lowerBound != string.startIndex { 
     let tildeIndex = string.index(before: substringRange.lowerBound) 
     if string[tildeIndex..<substringRange.lowerBound] == "~" { 
      let location = string.distance(from: string.startIndex, to: tildeIndex) 
      let length = string.distance(from: tildeIndex, to: substringRange.upperBound) 
      attributedString.addAttribute(NSFontAttributeName, value: boldAttribute, range: NSMakeRange(location, length)) 
     } 
    } 
}