2010-08-14 38 views
281

NSStringNSMutableStrings中的多種顏色是不可能的。所以我聽說NSAttributedStringiPad SDK 3.2(或3.2左右版本)推出的,並且可以在iPhone上從iPhone SDK 4.0 beta獲得。你如何使用NSAttributedString?

我想要一個有三種顏色的字符串。

我不使用3個單獨的NSStrings的原因是因爲三個NSAttributedString子串中每一個的長度經常變化,所以我寧願不使用任何計算來重新定位3個單獨的NSString對象。

如果使用NSAttributedString我該如何進行以下是可能的 - (如果不可能NSAttributed字符串,你會怎麼做):

alt text

編輯: 記住,@"first"@"second"@"third"將在任何時候被其他字符串替換。所以使用硬編碼的NSRange值將不起作用。

+0

[歸因字符串斯威夫特(http://stackoverflow.com/a/32269975/3681880) – Suragch 2016-01-06 07:24:18

+0

爲NSAttributeString雨燕代碼:http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift/27728516#27728516 – 2017-04-08 04:47:02

回答

464

在構建屬性字符串時,我更喜歡使用可變子類,只是爲了保持清潔。

話雖這麼說,這裏是你如何創建一個三色屬性串:

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"]; 
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)]; 
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)]; 
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)]; 

在瀏覽器中鍵入。 警告實現者

顯然你不打算在這樣的範圍內硬編碼。也許你反而可以做類似:

NSDictionary * wordToColorMapping = ....; //an NSDictionary of NSString => UIColor pairs 
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@""]; 
for (NSString * word in wordToColorMapping) { 
    UIColor * color = [wordToColorMapping objectForKey:word]; 
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName]; 
    NSAttributedString * subString = [[NSAttributedString alloc] initWithString:word attributes:attributes]; 
    [string appendAttributedString:subString]; 
    [subString release]; 
} 

//display string 
+0

謝謝戴夫。這應該工作,看起來像我只需要用'NSMakeRange(0,[字符串長度])'等替換硬編碼的'NSMakeRange'值等等,爲每個字符串。 +1 – 2010-08-14 07:20:02

+0

我對如何顯示此字符串非常感興趣?謝謝 – Jack 2010-09-24 11:22:16

+0

@Jack搜索「setAttributed」的文檔。這將讓你知道大多數控件接受屬性字符串 – 2010-09-25 15:29:44

113

的問題已經回答了......但我想說明如何添加陰影和改變與NSAttributedString字體爲好,這樣,當人們搜索這個話題,他們將不必繼續尋找。

#define FONT_SIZE 20 
#define FONT_HELVETICA @"Helvetica-Light" 
#define BLACK_SHADOW [UIColor colorWithRed:40.0f/255.0f green:40.0f/255.0f blue:40.0f/255.0f alpha:0.4f] 

NSString*myNSString = @"This is my string.\nIt goes to a second line.";     

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
       paragraphStyle.alignment = NSTextAlignmentCenter; 
      paragraphStyle.lineSpacing = FONT_SIZE/2; 
        UIFont * labelFont = [UIFont fontWithName:FONT_HELVETICA size:FONT_SIZE]; 
        UIColor * labelColor = [UIColor colorWithWhite:1 alpha:1]; 
         NSShadow *shadow = [[NSShadow alloc] init]; 
       [shadow setShadowColor : BLACK_SHADOW]; 
       [shadow setShadowOffset : CGSizeMake (1.0, 1.0)]; 
      [shadow setShadowBlurRadius : 1]; 

NSAttributedString *labelText = [[NSAttributedString alloc] initWithString : myNSString 
         attributes : @{ 
    NSParagraphStyleAttributeName : paragraphStyle, 
      NSKernAttributeName : @2.0, 
      NSFontAttributeName : labelFont, 
    NSForegroundColorAttributeName : labelColor, 
      NSShadowAttributeName : shadow }]; 

這裏是一個斯威夫特版本...

警告! 這適用於4s。

對於你必須改變所有的浮動值,以double值(因爲編譯器不能正常工作尚未)5S

斯威夫特枚舉的字體選擇:

enum FontValue: Int { 
    case FVBold = 1 , FVCondensedBlack, FVMedium, FVHelveticaNeue, FVLight, FVCondensedBold, FVLightItalic, FVUltraLightItalic, FVUltraLight, FVBoldItalic, FVItalic 
} 

斯威夫特陣列枚舉訪問(必要的,因爲枚舉不能使用 ' - '):

​​

斯威夫特屬性文本功能:

func myAttributedText (myString:String, mySize: Float, myFont:FontValue) -> (NSMutableAttributedString) { 

    let shadow = NSShadow() 
    shadow.shadowColor = UIColor.textShadowColor() 
    shadow.shadowOffset = CGSizeMake (1.0, 1.0) 
    shadow.shadowBlurRadius = 1 

    let paragraphStyle = NSMutableParagraphStyle.alloc() 
    paragraphStyle.lineHeightMultiple = 1 
    paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping 
    paragraphStyle.alignment = NSTextAlignment.Center 

    let labelFont = UIFont(name: helveticaFont(myFont.toRaw()), size: mySize) 
    let labelColor = UIColor.whiteColor() 

    let myAttributes :Dictionary = [NSParagraphStyleAttributeName : paragraphStyle, 
               NSKernAttributeName : 3, // (-1,5) 
               NSFontAttributeName : labelFont, 
            NSForegroundColorAttributeName : labelColor, 
              NSShadowAttributeName : shadow] 

    let myAttributedString = NSMutableAttributedString (string: myString, attributes:myAttributes) 

    // add new color 
    let secondColor = UIColor.blackColor() 
    let stringArray = myString.componentsSeparatedByString(" ") 
    let firstString: String? = stringArray.first 
    let letterCount = countElements(firstString!) 
    if firstString { 
     myAttributedString.addAttributes([NSForegroundColorAttributeName:secondColor], range:NSMakeRange(0,letterCount)) 
    } 

    return myAttributedString 
} 

用於字符串數組查找範圍第一個和最後延伸:

extension Array { 
    var last: T? { 
     if self.isEmpty { 
      NSLog("array crash error - please fix") 
      return self [0] 
     } else { 
      return self[self.endIndex - 1] 
     } 
    } 
} 

extension Array { 
    var first: T? { 
     if self.isEmpty { 
      NSLog("array crash error - please fix") 
      return self [0] 
     } else { 
      return self [0] 
     } 
    } 
} 

新的顏色:

extension UIColor { 
    class func shadowColor() -> UIColor { 
     return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.3) 
    } 
    class func textShadowColor() -> UIColor { 
     return UIColor(red: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 0.5) 
    } 
    class func pastelBlueColor() -> UIColor { 
     return UIColor(red: 176.0/255.0, green: 186.0/255.0, blue: 255.0/255.0, alpha: 1) 
    } 
    class func pastelYellowColor() -> UIColor { 
     return UIColor(red: 255.0/255.0, green: 238.0/255.0, blue: 140.0/255.0, alpha: 1) 
    } 
} 

我的宏替換:

enum MyConstants: Float { 
    case CornerRadius = 5.0 
} 

我的按鈕壺w^/歸屬文字:

func myButtonMaker (myView:UIView) -> UIButton { 

    let myButton = UIButton.buttonWithType(.System) as UIButton 
    myButton.backgroundColor = UIColor.pastelBlueColor() 
    myButton.showsTouchWhenHighlighted = true; 
    let myCGSize:CGSize = CGSizeMake(100.0, 50.0) 
    let myFrame = CGRectMake(myView.frame.midX - myCGSize.height,myView.frame.midY - 2 * myCGSize.height,myCGSize.width,myCGSize.height) 
    myButton.frame = myFrame 
    let myTitle = myAttributedText("Button",20.0,FontValue.FVLight) 
    myButton.setAttributedTitle(myTitle, forState:.Normal) 

    myButton.layer.cornerRadius = myButton.bounds.size.width/MyConstants.CornerRadius.toRaw() 
    myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) 
    myButton.tag = 100 
    myButton.bringSubviewToFront(myView) 
    myButton.layerGradient() 

    myView.addSubview(myButton) 

    return myButton 
} 

我UIView /的UILabel壺W /屬性文本,陰影和圓角:

func myLabelMaker (myView:UIView) -> UIView { 

    let myFrame = CGRectMake(myView.frame.midX/2 , myView.frame.midY/2, myView.frame.width/2, myView.frame.height/2) 
    let mylabelFrame = CGRectMake(0, 0, myView.frame.width/2, myView.frame.height/2) 

    let myBaseView = UIView() 
    myBaseView.frame = myFrame 
    myBaseView.backgroundColor = UIColor.clearColor() 

    let myLabel = UILabel() 
    myLabel.backgroundColor=UIColor.pastelYellowColor() 
    myLabel.frame = mylabelFrame 

    myLabel.attributedText = myAttributedText("This is my String",20.0,FontValue.FVLight) 
    myLabel.numberOfLines = 5 
    myLabel.tag = 100 
    myLabel.layer.cornerRadius = myLabel.bounds.size.width/MyConstants.CornerRadius.toRaw() 
    myLabel.clipsToBounds = true 
    myLabel.layerborders() 

    myBaseView.addSubview(myLabel) 

    myBaseView.layerShadow() 
    myBaseView.layerGradient() 

    myView.addSubview(myBaseView) 

    return myLabel 
} 

通用添加陰影:

func viewshadow<T where T: UIView> (shadowObject: T) 
{ 
    let layer = shadowObject.layer 
    let radius = shadowObject.frame.size.width/MyConstants.CornerRadius.toRaw(); 
    layer.borderColor = UIColor.whiteColor().CGColor 
    layer.borderWidth = 0.8 
    layer.cornerRadius = radius 
    layer.shadowOpacity = 1 
    layer.shadowRadius = 3 
    layer.shadowOffset = CGSizeMake(2.0,2.0) 
    layer.shadowColor = UIColor.shadowColor().CGColor 
} 

視圖擴展視圖樣式:

extension UIView { 
    func layerborders() { 
     let layer = self.layer 
     let frame = self.frame 
     let myColor = self.backgroundColor 
     layer.borderColor = myColor.CGColor 
     layer.borderWidth = 10.8 
     layer.cornerRadius = layer.borderWidth/MyConstants.CornerRadius.toRaw() 
    } 

    func layerShadow() { 
     let layer = self.layer 
     let frame = self.frame 
     layer.cornerRadius = layer.borderWidth/MyConstants.CornerRadius.toRaw() 
     layer.shadowOpacity = 1 
     layer.shadowRadius = 3 
     layer.shadowOffset = CGSizeMake(2.0,2.0) 
     layer.shadowColor = UIColor.shadowColor().CGColor 
    } 

    func layerGradient() { 
     let layer = CAGradientLayer() 
     let size = self.frame.size 
     layer.frame.size = size 
     layer.frame.origin = CGPointMake(0.0,0.0) 
     layer.cornerRadius = layer.bounds.size.width/MyConstants.CornerRadius.toRaw(); 

     var color0 = CGColorCreateGenericRGB(250.0/255, 250.0/255, 250.0/255, 0.5) 
     var color1 = CGColorCreateGenericRGB(200.0/255, 200.0/255, 200.0/255, 0.1) 
     var color2 = CGColorCreateGenericRGB(150.0/255, 150.0/255, 150.0/255, 0.1) 
     var color3 = CGColorCreateGenericRGB(100.0/255, 100.0/255, 100.0/255, 0.1) 
     var color4 = CGColorCreateGenericRGB(50.0/255, 50.0/255, 50.0/255, 0.1) 
     var color5 = CGColorCreateGenericRGB(0.0/255, 0.0/255, 0.0/255, 0.1) 
     var color6 = CGColorCreateGenericRGB(150.0/255, 150.0/255, 150.0/255, 0.1) 

     layer.colors = [color0,color1,color2,color3,color4,color5,color6] 
     self.layer.insertSublayer(layer, atIndex: 2) 
    } 
} 

實際視圖確實加載了功能:

func buttonPress (sender:UIButton!) { 
    NSLog("%@", "ButtonPressed") 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let myLabel = myLabelMaker(myView) 
    let myButton = myButtonMaker(myView) 

    myButton.addTarget(self, action: "buttonPress:", forControlEvents:UIControlEvents.TouchUpInside) 

    viewshadow(myButton) 
    viewshadow(myLabel) 

} 
31

我認爲,使用regular expressions來找到應用屬性的範圍是一種非常方便的方法。我是這樣做的:

NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText]; 

NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch]; 
if (range.location != NSNotFound) { 
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range]; 
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range]; 
} 

NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]]; 
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch]; 
if (range.location != NSNotFound) { 
    [goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range]; 
    [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range]; 
} 

[self.textView setAttributedText:goodText]; 

我正在搜索可用屬性的列表,並沒有在這裏和類引用的第一頁中找到它們。所以我決定在這裏發佈有關這方面的信息。

Standard Attributes

歸因串支持文本以下標準屬性。如果密鑰不在字典中,則使用下面描述的默認值。

NSString *NSFontAttributeName; 
NSString *NSParagraphStyleAttributeName; 
NSString *NSForegroundColorAttributeName; 
NSString *NSUnderlineStyleAttributeName; 
NSString *NSSuperscriptAttributeName; 
NSString *NSBackgroundColorAttributeName; 
NSString *NSAttachmentAttributeName; 
NSString *NSLigatureAttributeName; 
NSString *NSBaselineOffsetAttributeName; 
NSString *NSKernAttributeName; 
NSString *NSLinkAttributeName; 
NSString *NSStrokeWidthAttributeName; 
NSString *NSStrokeColorAttributeName; 
NSString *NSUnderlineColorAttributeName; 
NSString *NSStrikethroughStyleAttributeName; 
NSString *NSStrikethroughColorAttributeName; 
NSString *NSShadowAttributeName; 
NSString *NSObliquenessAttributeName; 
NSString *NSExpansionAttributeName; 
NSString *NSCursorAttributeName; 
NSString *NSToolTipAttributeName; 
NSString *NSMarkedClauseSegmentAttributeName; 
NSString *NSWritingDirectionAttributeName; 
NSString *NSVerticalGlyphFormAttributeName; 
NSString *NSTextAlternativesAttributeName; 

NSAttributedString programming guide

一個完整的類引用是here

+0

感謝列出屬性鍵(很難找到其他) – 2014-12-23 21:42:21

+0

您如何在Swift中做到這一點? – Tom 2015-03-06 22:40:24

14

我寫了幫手,輕鬆添加屬性:

- (void)addColor:(UIColor *)color substring:(NSString *)substring; 
- (void)addBackgroundColor:(UIColor *)color substring:(NSString *)substring; 
- (void)addUnderlineForSubstring:(NSString *)substring; 
- (void)addStrikeThrough:(int)thickness substring:(NSString *)substring; 
- (void)addShadowColor:(UIColor *)color width:(int)width height:(int)height radius:(int)radius substring:(NSString *)substring; 
- (void)addFontWithName:(NSString *)fontName size:(int)fontSize substring:(NSString *)substring; 
- (void)addAlignment:(NSTextAlignment)alignment substring:(NSString *)substring; 
- (void)addColorToRussianText:(UIColor *)color; 
- (void)addStrokeColor:(UIColor *)color thickness:(int)thickness substring:(NSString *)substring; 
- (void)addVerticalGlyph:(BOOL)glyph substring:(NSString *)substring; 

https://github.com/shmidt/MASAttributes

您可以通過的CocoaPods安裝也:pod 'MASAttributes', '~> 1.0.0'

9

我總是發現,與歸屬串合作是一個令人難以置信的長篇大論和繁瑣的過程。

所以我做了一個Mac App,爲你創建所有的代碼。

https://itunes.apple.com/us/app/attributed-string-creator/id730928349?mt=12

+0

此處還有一個用於使NSAttributed字符串更容易一些的類別/博文。 http://www.raizlabs.com/dev/2014/03/nsattributedstring-creation-helpers/ – 2014-03-12 21:52:44

10

由於iOS的7,您可以使用NSAttributedString與HTML語法:

NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"string"  withExtension:@"html"]; 
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString 
                         options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} 
                      documentAttributes:nil 
                         error:nil]; 
textView.attributedText = stringWithHTMLAttributes;// you can use a label also 

你要添加的文件 「string.html」 你凸出,並且HTML的內容可以是像這樣:

<html> 
    <head> 
    <style type="text/css"> 
     body { 
     font-size: 15px; 
     font-family: Avenir, Arial, sans-serif; 
     } 
     .red { 
     color: red; 
     } 
     .green { 
     color: green; 
     } 
     .blue { 
     color: blue; 
     } 
    </style> 
    </head> 
    <body> 
    <span class="red">first</span><span class="green">second</span><span class="blue">third</span> 
    </body> 
</html> 

現在,你可以使用NSAttributedString只要你想,即使沒有HTML文件,例如像:

//At the top of your .m file 
#define RED_OCCURENCE -red_occurence- 
#define GREEN_OCCURENCE -green_occurence- 
#define BLUE_OCCURENCE -blue_occurence- 
#define HTML_TEMPLATE @"<span style=\"color:red\">-red_occurence-</span><span style=\"color:green\">-green_occurence-</span><span style=\"color:blue\">-blue_occurence-</span></body></html>" 

//Where you need to use your attributed string 
NSString *string = [HTML_TEMPLATE stringByReplacingOccurrencesOfString:RED_OCCURENCE withString:@"first"] ; 
string = [string stringByReplacingOccurrencesOfString:GREEN_OCCURENCE withString:@"second"]; 
string = [string stringByReplacingOccurrencesOfString:BLUE_OCCURENCE withString:@"third"]; 

NSData* cData = [string dataUsingEncoding:NSUTF8StringEncoding]; 

NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:cData 
                       options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} 
                     documentAttributes:nil 
                        error:nil]; 
textView.attributedText = stringWithHTMLAttributes; 

Source

2

可以在Swift加載HTML屬性串如下

var Str = NSAttributedString(
    data: htmlstring.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true), 
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
    documentAttributes: nil, 
    error: nil) 

    label.attributedText = Str 

從文件

if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) { 

    let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil) 
     textView.attributedText = attributedString 
     textView.editable = false 
    } 

http://sketchytech.blogspot.in/2013/11/creating-nsattributedstring-from-html.html

加載

和設置字符串,按您的要求的屬性....遵循這個..
http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/

1
- (void)changeColorWithString:(UILabel *)uilabel stringToReplace:(NSString *) stringToReplace uiColor:(UIColor *) uiColor{ 
    NSMutableAttributedString *text = 
    [[NSMutableAttributedString alloc] 
    initWithAttributedString: uilabel.attributedText]; 

    [text addAttribute: NSForegroundColorAttributeName value:uiColor range:[uilabel.text rangeOfString:stringToReplace]]; 

    [uilabel setAttributedText: text]; 

} 
19

該解決方案將適用於任何長度

NSString *strFirst = @"Anylengthtext"; 
NSString *strSecond = @"Anylengthtext"; 
NSString *strThird = @"Anylengthtext"; 

NSString *strComplete = [NSString stringWithFormat:@"%@ %@ %@",strFirst,strSecond,strThird]; 

NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete]; 

[attributedString addAttribute:NSForegroundColorAttributeName 
       value:[UIColor redColor] 
       range:[strComplete rangeOfString:strFirst]]; 

[attributedString addAttribute:NSForegroundColorAttributeName 
       value:[UIColor yellowColor] 
       range:[strComplete rangeOfString:strSecond]]; 

[attributedString addAttribute:NSForegroundColorAttributeName 
       value:[UIColor blueColor] 
       range:[strComplete rangeOfString:strThird]]; 


self.lblName.attributedText = attributedString; 
+2

感謝您爲我工作 – 2016-06-21 11:48:58

+0

請注意,對於SWIFT,您仍然需要使用NSString,因爲範圍,請檢查此回答:http://stackoverflow.com/a/27041376/1736679 – Efren 2017-05-10 01:42:51

2

我做了一個庫,使這個很容易。查看ZenCopy: https://github.com/trifl/ZenCopy

您可以創建Style對象,和/或將它們設置爲鍵以供稍後參考。就像這樣:

ZenCopy.manager.config.setStyles { 
    return [ 
     "token": Style(
      color: .blueColor(), // optional 
      // fontName: "Helvetica", // optional 
      fontSize: 14 // optional 
     ) 
    ] 
} 

然後,您可以輕鬆地構建字符串和他們的風格,並有PARAMS :)

label.attributedText = attributedString(
           ["$0 ".style("token") "is dancing with ", "$1".style("token")], 
          args: ["JP", "Brock"] 
) 

你也可以風格事情正則表達式搜索很容易!

let atUserRegex = "(@[A-Za-z0-9_]*)" 
mutableAttributedString.regexFind(atUserRegex, addStyle: "token") 

這將使用'標記'風格對所有帶有'@'的單詞進行樣式設置。 (例如。@jpmcglone)

我需要仍然得到它的工作瓦特/一切NSAttributedString所提供的,但我想的fontName,fontSize的和顏色覆蓋大部分吧。很快會大量更新的:)

我可以幫你開始使用這個,如果你需要的。同時尋找反饋,所以如果它讓你的生活更輕鬆,我會說任務已經完成。

0

爲了解決這樣那樣的斯威夫特被稱爲Atributika我創建庫的問題。

let str = "<r>first</r><g>second</g><b>third</b>".style(tags: 
     Style("r").foregroundColor(.red), 
     Style("g").foregroundColor(.green), 
     Style("b").foregroundColor(.blue)).attributedString 

label.attributedText = str 

你可以在這裏https://github.com/psharanda/Atributika

2

發現它與屬性串擴展更容易的解決方案。

extension NSMutableAttributedString { 

    // this function attaches color to string  
    func setColorForText(textToFind: String, withColor color: UIColor) { 
     let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive) 
     self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) 
    } 

} 

試試這個,看到(在夫特3 & 4測試)

let label = UILabel() 
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30) 
let first = "first" 
let second = "second" 
let third = "third" 
let stringValue = "\(first)\(second)\(third)" // or direct assign single string value like "firstsecondthird" 

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) 
attributedString.setColorForText(textToFind: first, withColor: UIColor.red) // use variable for string "first" 
attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second" 
attributedString.setColorForText(textToFind: third, withColor: UIColor.blue) 
label.font = UIFont.systemFont(ofSize: 26) 
label.attributedText = attributedString 
self.view.addSubview(label) 

在這裏預期的結果:

enter image description here

2

在夫特4:

let string:NSMutableAttributedString = { 

    let mutableString = NSMutableAttributedString(string: "firstsecondthird") 

    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: NSRange(location: 0, length: 5)) 
    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green , range: NSRange(location: 5, length: 6)) 
    mutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: NSRange(location: 11, length: 5)) 
    return mutableString 
}() 

print(string) 
+0

請不要發佈相同的答案多個問題。發佈一個很好的答案,然後投票/標記以重複關閉其他問題。如果問題不重複,*定製你對問題的回答。* – 2017-10-12 19:22:51

+0

我想在Swift中給出答案。我接受了它的重複。不要期待投票 – 2017-10-12 19:24:11

+0

道歉。我已經刪除了答案 – 2017-10-12 19:28:51

0

斯威夫特4

let combination = NSMutableAttributedString() 

var part1 = NSMutableAttributedString() 
var part2 = NSMutableAttributedString() 
var part3 = NSMutableAttributedString() 

let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)] 

let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)] 

let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15), 
           NSAttributedStringKey.foregroundColor: UIColor.red] 

if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{ 
    part1 = NSMutableAttributedString(string: "first", attributes: regular) 

} 
if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{ 
    part2 = NSMutableAttributedString(string: "second", attributes: bold) 
} 

if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{ 
    part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor) 
} 

combination.append(part1) 
combination.append(part2) 
combination.append(part3) 

屬性列表,請參閱這裏NSAttributedStringKey on Apple Docs

相關問題