Как вы используете NSAttributedString?

Использование нескольких цветов в NSString или NSMutableStrings невозможно. Итак, я немного слышал о NSAttributedString, который был представлен с iPad SDK 3.2 (или около 3.2) и доступен на iPhone с iPhone SDK 4.0 beta < / сильный>.

Я хотел бы иметь строку трех цветов.

Причина, по которой я не использую 3 отдельных NSStrings, заключается в том, что длина каждой из трех NSAttributedString подстрок часто меняется, и поэтому я бы предпочел не использовать какие-либо вычисления для изменения положения 3 отдельных NSString объектов.

Если это возможно с помощью NSAttributedString, как мне сделать следующее - (если это невозможно со строкой NSAttributed, как бы вы это сделали):

альтернативный текст

Изменить: помните, что @"first", @"second" и @"third" будут заменены другими строками в любое время. Поэтому использование жестко запрограммированных значений NSRange не сработает.


person Brock Woolf    schedule 14.08.2010    source источник
comment
Строки с атрибутами в Swift   -  person Suragch    schedule 06.01.2016
comment
Код Swift для NSAttributeString: stackoverflow.com/questions/27728466/   -  person Kirit Modi    schedule 08.04.2017


Ответы (14)


При построении строк с атрибутами я предпочитаю использовать изменяемый подкласс, чтобы все было чище.

При этом, вот как вы создаете трехцветную атрибутивную строку:

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
person Dave DeLong    schedule 14.08.2010
comment
Спасибо, Дэйв. Это должно сработать, похоже, мне просто нужно заменить жестко запрограммированные значения NSMakeRange на NSMakeRange(0,[string length]) и т.д. для каждой строки. +1 - person Brock Woolf; 14.08.2010
comment
@Jack найдите в документации setAttributed. Это позволит вам узнать о большинстве элементов управления, которые принимают строки с атрибутами. - person Dave DeLong; 25.09.2010
comment
Не могли бы вы сообщить мне, как присвоить метке строку с атрибутами? - person Pooja M. Bohora; 21.12.2011
comment
такой же вопрос здесь ?? может ли кто-нибудь написать код для присвоения атрибутивной строки метке? - person Syed Faraz Haider Zaidi; 16.02.2012
comment
@SyedFarazHaiderZaidi В UIKit нет ничего, что могло бы принимать NSAttributedString. Однако есть вещи с открытым исходным кодом, такие как OHAttributedLabel. - person Dave DeLong; 16.02.2012
comment
Если вы используете CoreText.framework в iOS, вам, вероятно, понадобится константа kCTForegroundColorAttributeName, а не NSForegroundColorAttributeName. - person Phil Calvin; 18.05.2012
comment
@PhilCalvin Почему именно? Разве NSForegroundColorAttributeName не обернулось бы вокруг константы CoreText? - person SpacyRicochet; 15.06.2012
comment
@SpacyRicochet NSForegroundColorAttributeName не определен в iOS, по крайней мере, если вы компилируете с использованием SDK 5.1. Для MacOS он определен в ApplicationKit. - person Phil Calvin; 15.06.2012
comment
В iOS6, которая только что была выпущена (так что я могу говорить без соглашения о неразглашении), вы можете делать такие вещи, как myLabel.attributedText = attributedString; Это о долбанутом времени ... Я ждал этой функции много лет. - person Kevin Hoffman; 20.09.2012
comment
Я использовал его, но он превратил мою этикетку в одну строку. Я делаю numberOfLines равным 2 как из IB, так и из кода, но никакого эффекта. Установка свойства .text работает нормально (предложения отображаются в 2 строки), но, задав свойство attributedText для UILabel, сделайте его одной строкой. У кого-нибудь такая же проблема? и какие решения? - person Ans; 19.03.2013
comment
В любом случае, чтобы получить атрибуты из NSAttributedString позже? Мне нужно отобразить цветной текст с помощью другого движка. - person Jonny; 20.01.2014
comment
@Jonny -[NSAttributedString enumerateAttributesInRange:options:usingBlock:] - person Dave DeLong; 20.01.2014
comment
ВНИМАНИЕ: ключи словаря неупорядочены. Не используйте приведенный выше код, вы потеряете контроль над порядком отображения ваших строк. - person Matt-Lloyd; 17.04.2014
comment
Caveat implementor - это фраза, которую я буду использовать в ближайшем будущем. - person Nate Symer; 19.07.2014
comment
@ Matt-Lloyd, два словаря NSDictionaries, которые он использует в своих примерах, предназначены для ›сопоставления цветов и атрибутов каждой NSAttributedString. Порядок слов не изменяется. - person solidcell; 25.08.2015
comment
когда я перемещаю указатель начала диапазона ›чем 0, приложение вылетает из-за выхода за пределы поля! - person Suhayb; 12.03.2018

На вопрос уже дан ответ ... но я хотел показать, как добавить тень и изменить шрифт с помощью 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 }];

Вот версия Swift ...

Предупреждение! Это работает в течение 4 секунд.

Для 5s вам нужно изменить все значения Float на значения Double (потому что компилятор еще не работает правильно)

Быстрое перечисление для выбора шрифта:

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

Быстрый массив для доступа к перечислению (необходим, потому что перечисление не может использовать '-'):

func helveticaFont (index:Int) -> (String) {
    let fontArray = [
    "HelveticaNeue-Bold",
    "HelveticaNeue-CondensedBlack",
    "HelveticaNeue-Medium",
    "HelveticaNeue",
    "HelveticaNeue-Light",
    "HelveticaNeue-CondensedBold",
    "HelveticaNeue-LightItalic",
    "HelveticaNeue-UltraLightItalic",
    "HelveticaNeue-UltraLight",
    "HelveticaNeue-BoldItalic",
    "HelveticaNeue-Italic",
    ]
    return fontArray[index]
}

Текстовая функция Swift с атрибутами:

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
}

мой создатель кнопок с приписанным текстом:

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 с атрибутированным текстом, тенью и скругленными углами:

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)

}
person MGM    schedule 20.03.2013

Я думаю, это очень удобный способ использовать 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];

Я искал список доступных атрибутов и не нашел их здесь и на первой странице справочника по классам. Поэтому я решил разместить здесь информацию об этом.

Стандартные атрибуты

Строки с атрибутами поддерживают следующие стандартные атрибуты текста. Если ключа нет в словаре, используйте значения по умолчанию, описанные ниже.

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

Полная ссылка на класс находится здесь.

person Denis Kutlubaev    schedule 16.08.2013
comment
спасибо за перечисление ключей атрибутов (иначе трудно найти) - person Ali Saeed; 24.12.2014
comment
Как бы вы сделали это в Swift? - person Thomas Martinez; 07.03.2015

Это решение подойдет для любой длины.

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;
person Seema Sharma    schedule 04.02.2016
comment
Обратите внимание, что для SWIFT вам все равно нужно использовать NSString из-за диапазонов, ознакомьтесь с этим ответом: stackoverflow.com/a/27041376/ 1736679 - person Efren; 10.05.2017

Я написал помощник, чтобы легко добавлять атрибуты:

- (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'

person Shmidt    schedule 06.10.2013

Начиная с 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;

Источник

person André Rodrigues    schedule 04.03.2014

Я всегда считал работу со строками с атрибутами невероятно долгим и утомительным процессом.

Итак, я сделал приложение для Mac, которое создает для вас весь код.

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

person Mark Bridges    schedule 14.11.2013
comment
Также вот пост в категории / блоге о том, как немного упростить строку NSAttributed. raizlabs.com/dev/2014/03/nsattributedstring-creation-helpers - person Alex Rouse; 13.03.2014

Более простое решение с атрибутированным расширением строки.

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)
    }

}

Попробуйте это и посмотрите (протестировано в Swift 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)

Вот ожидаемый результат:

введите описание изображения здесь

person Krunal    schedule 12.10.2017

В Swift 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)
person garg    schedule 12.10.2017
comment
Пожалуйста, не публикуйте одинаковые ответы на несколько вопросов. Опубликуйте один хороший ответ, затем проголосуйте / отметьте, чтобы закрыть другие вопросы как дубликаты. Если вопрос не повторяется, адаптируйте свои ответы к вопросу. - person Paul Roub; 12.10.2017
comment
Пытаюсь ответить на Swift. Я принял его дубликат. Не ожидая голосов - person garg; 12.10.2017
comment
Извинения. Я удалил ответ - person garg; 12.10.2017

Вы можете загрузить HTML строку с атрибутами в Swift следующим образом

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

   label.attributedText = Str  

Чтобы загрузить html из файла

   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/

person EI Captain v2.0    schedule 13.05.2015

Я сделал библиотеку, которая делает это намного проще. Попробуйте ZenCopy.

Вы можете создавать объекты Style и / или устанавливать для них ключи, которые будут использоваться позже. Нравится:

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

Затем вы можете легко создавать строки И стилизовать их И иметь параметры :)

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 и цвет покрывают большую часть этого. Ожидайте много обновлений в ближайшее время :)

Я могу помочь вам начать с этого, если вам нужно. Также ищу обратную связь, поэтому, если это облегчит вашу жизнь, я бы сказал, что миссия выполнена.

person JP.    schedule 20.02.2016

Для решения подобных задач я в swift создал библиотеку под названием Атрибутика.

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.

person Pavel Sharanda    schedule 22.02.2017

Swift 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 в Apple Docs

person Shan Ye    schedule 09.02.2018

Супер простой способ сделать это.

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

Для получения более подробной информации нажмите здесь; https://github.com/iOSTechHub/AttributedString

person Ashish Chauhan    schedule 02.09.2018