2011-12-15 80 views
3

我知道可以將屬性應用於NSAttributedString。對NSAttributedString的不同部分應用不同的屬性

但是,我們如何應用不同的屬性到相同的屬性字符串。

爲字符串「這是一個歸因文本」。

我們如何設置一個特定的屬性(背景顏色或前景色)爲「這是」另一個屬性(背景色或前景色)爲「屬性文本」。

有什麼辦法可以實現這個....?

還有什麼辦法可以在iOS中設置NSAttributedString的背景顏色嗎?

回答

4

充分利用屬性串的可變副本,然後使用:

-setAttributes:範圍:
-addAttributes:範圍:
-addAttribute:值:範圍:
-removeAttributes:範圍:

例如,要設置一個紅色的頭四個字母:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy]; 
CGColorRef redClr = [UIColor redColor].CGColor; 
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName]; 
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)]; 

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

在iOS上沒有內置的繪製背景顏色的方法。您可以爲該屬性創建自定義字符串常量,例如「MyBackgroundColorAttributeName」,然後您必須自己繪製它。

+0

非常感謝wekwa。它的工作。 – Arun 2011-12-16 11:35:19

2

我正在使用下面的擴展名來改變「NSMutableAttributedString」顏色,它很好地做了這個技巧。它可以被用來作爲模板

extension NSMutableAttributedString 
{ 
     func changeColourOf(_ terms:[String],toThisColour termsColour:UIColor,andForegroundColour fontColour:UIColor) 
{ 
    // Set your foreground Here 
    self.addAttributes([NSForegroundColorAttributeName:fontColour], range:NSMakeRange(0, self.length)) 
    //Convert "NSMutableAttributedString" to a NSString 
    let string = self.string as NSString 
    //Create a for loop for ther terms array 
    for term in terms 
    { 
     //This will be the range of each term 
     let underlineRange = string.range(of: term) 
     //Finally change the term colour 
     self.addAttribute(NSForegroundColorAttributeName, value: termsColour, range: underlineRange) 
    }}} 

let someMutableStr = NSMutableAttributedString(string: "Hello World 2017 !") 
someMutableStr.changeColourOf(["Hello","2017"], toThisColour: .blue, theStringFontColour: .red) 

enter image description here