2017-04-22 67 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)) 
     } 
    } 
}