2017-04-22 5 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)」と私は私が2 nsmutableattributedstringsを追加することはできませんというエラーを取得しnsmutableattributedstringとして「finalStr」をキャストした場合 –

+0

Ahhh。私は答えを更新しました。これはあなたの問題を解決するはずです。 – 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)) 
     } 
    } 
} 
関連する問題