Jak korzystać z NSAttributString?

308

Wiele kolorów w NSStringlub NSMutableStringsnie jest możliwe. Więc słyszałem trochę o tym, NSAttributedStringktóry został wprowadzony z iPadem SDK 3.2 (lub około 3.2) i jest dostępny na iPhonie od iPhone SDK 4.0 beta .

Chciałbym mieć sznurek, który ma trzy kolory.

Powodem, dla którego nie używam 3 oddzielnych ciągów NSS, jest to, że długość każdego z trzech NSAttributedStringpodciągów często się zmienia, więc wolałbym nie używać żadnych obliczeń do zmiany położenia 3 oddzielnych NSStringobiektów.

Jeśli jest to możliwe przy użyciu, NSAttributedStringjak to zrobić, wykonaj następujące czynności - (jeśli nie jest to możliwe z ciągiem NSAttorted, jak to zrobić):

alternatywny tekst

Edit: Pamiętaj @"first", @"second"i @"third"zostanie zastąpiony przez inne ciągi w dowolnym momencie. Tak więc używanie zakodowanych wartości NSRange nie będzie działać.

Brock Woolf
źródło
Kod Swift dla NSAttributeString: stackoverflow.com/questions/27728466/…
Kirit Modi

Odpowiedzi:

479

Podczas budowania przypisywanych ciągów wolę używać zmiennej podklasy, aby zachować czystość.

Biorąc to pod uwagę, oto jak utworzyć trójkolorowy ciąg znaków:

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)];

wpisany w przeglądarce. implementator zastrzeżenia

Oczywiście nie będziesz programował na stałe w takich zakresach. Być może zamiast tego możesz zrobić coś takiego:

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
Dave DeLong
źródło
4
Czy możesz dać mi znać, jak przypisać przypisany ciąg do etykiety?
Pooja M. Bohora,
5
@SyedFarazHaiderZaidi Nie ma nic wbudowanego w UIKit, który akceptuje NSAttributedString. Istnieją jednak rzeczy typu open source, takie jak OHAttributLabel .
Dave DeLong
4
Jeśli używasz CoreText.framework na iOS, prawdopodobnie będziesz potrzebować stałej kCTForegroundColorAttributeNamezamiast NSForegroundColorAttributeName.
Phil Calvin
32
W iOS6, który właśnie został wydany (więc mogę rozmawiać bez NDA), możesz robić rzeczy takie jak myLabel.attributeText = attortedString; Chodzi o dziwny czas ... Czekałem na tę funkcję od lat.
Kevin Hoffman
5
OSTRZEŻENIE: Klawisze słownika są nieuporządkowane. Nie używaj powyższego kodu, stracisz kontrolę nad kolejnością wyświetlania łańcuchów.
Matt-Lloyd
117

Odpowiedź na pytanie jest już udzielona ... ale chciałem pokazać, jak dodać cień i zmienić czcionkę za pomocą NSAttributString, aby ludzie szukający tego tematu nie musieli dalej szukać.

#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 }];

Oto wersja Swift ...

Ostrzeżenie! Działa to przez 4s.

Przez 5s musisz zmienić wszystkie wartości Float na Double wartości (ponieważ kompilator jeszcze nie działa poprawnie)

Szybkie wyliczanie do wyboru czcionek:

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

Szybka tablica dla dostępu do enum (wymagana, ponieważ enum nie może używać „-”):

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

Szybka przypisana funkcja tekstu:

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
}

pierwsze i ostatnie rozszerzenie używane do znajdowania zakresów w tablicy ciągów:

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

nowe kolory:

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

moja zamiana makr:

enum MyConstants: Float {
    case CornerRadius = 5.0
}

mój twórca przycisków z tekstem:

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
}

mój UIView / UILabel maker z przypisanym tekstem, cieniem i zaokrąglonymi rogami:

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
}

ogólny cień dodaj:

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
}

zobacz rozszerzenie dla stylu widoku:

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

rzeczywisty widok załadował funkcję:

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)

}
MGM
źródło
33

Myślę, że jest to bardzo wygodny sposób regular expressionsna znalezienie zakresu zastosowania atrybutów. Oto jak to zrobiłem:

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];

Szukałem listy dostępnych atrybutów i nie znalazłem ich tutaj ani na pierwszej stronie referencji do zajęć. Postanowiłem więc opublikować tutaj informacje na ten temat.

Standardowe atrybuty

Przypisane ciągi znaków obsługują następujące standardowe atrybuty tekstu. Jeśli klucza nie ma w słowniku, użyj domyślnych wartości opisanych poniżej.

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;

Przewodnik programowania NSAttributString

Pełne odniesienie do klasy znajduje się tutaj .

Denis Kutlubaev
źródło
dzięki za wystawienie kluczy atrybutów (tak trudno znaleźć inaczej)
Ali Saeed
Jak byś to zrobił w Swift?
Thomas Martinez,
25

To rozwiązanie będzie działać na dowolną długość

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;
Seema Sharma
źródło
Pamiętaj, że w przypadku SWIFT nadal musisz używać NSString, ze względu na zakresy sprawdź tę odpowiedź: stackoverflow.com/a/27041376/1736679
Efren
15

Napisałem pomocnika, aby łatwo dodawać atrybuty:

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

Możesz zainstalować za pośrednictwem CocoaPods również: pod 'MASAttributes', '~> 1.0.0'

Shmidt
źródło
11

Od iOS 7 możesz używać NSAttributedStringskładni 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

Musisz dodać plik „string.html” do swojego projektu, a zawartość HTML może być taka:

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

Teraz możesz używać, NSAttributedStringjak chcesz, nawet bez pliku HTML, na przykład:

//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;

Źródło

André Rodrigues
źródło
3

Łatwiejsze rozwiązanie dzięki przypisanemu przedłużeniu łańcucha.

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

}

Spróbuj tego i zobacz (Testowane w Swift 3 i 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)

Oto oczekiwany wynik:

wprowadź opis zdjęcia tutaj

Krunal
źródło
3

W 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)
Anargit garg
źródło
1
Nie publikuj identycznych odpowiedzi na wiele pytań. Opublikuj jedną dobrą odpowiedź, a następnie głosuj / oznacz, aby zamknąć pozostałe pytania jako duplikaty. Jeśli pytanie nie jest duplikatem, dopasuj swoje odpowiedzi do pytania.
Paul Roub,
Próbuję udzielić odpowiedzi w Swift. Zaakceptowałem jego duplikat. Nie spodziewam się głosów
Ankit garg
Przeprosiny.
Usunąłem
2

Możesz załadować HTMLprzypisany ciąg w Swiftnastępujący sposób

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

   label.attributedText = Str  

Aby załadować htmlz pliku

   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-nsattributstring-from-html.html

I ustaw ciąg zgodnie z wymaganym atrybutem .... postępuj zgodnie z tym ..
http://makeapppie.com/2014/10/20/swift-swift-using-attorted-strings-in-swift/

EI Captain v2.0
źródło
2

Stworzyłem bibliotekę, która znacznie ułatwia to zadanie. Sprawdź ZenCopy.

Możesz tworzyć obiekty Style i / lub ustawiać je na klucze, aby odwoływały się później. Lubię to:

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

Następnie możesz łatwo konstruować łańcuchy i stylizować je ORAZ mieć parametry :)

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

Możesz także łatwo stylizować rzeczy dzięki wyszukiwaniu wyrażeń regularnych!

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

Spowoduje to stylizowanie wszystkich słów za pomocą „@” przed stylem „token”. (np. @jpmcglone)

Muszę nadal działać, bo wszystko NSAttributedStringma do zaoferowania, ale myślę fontName, fontSizeże większość z nich pokrywa kolor. Spodziewaj się wkrótce wielu aktualizacji :)

Mogę pomóc ci zacząć od tego, jeśli potrzebujesz. Również szukam informacji zwrotnych, więc jeśli to ułatwi ci życie, powiedziałbym, że misja została wykonana.

JP.
źródło
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];

}
zeisuke
źródło
0

Aby rozwiązać tego rodzaju problemy, szybko stworzyłem bibliotekę o nazwie 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

Można go znaleźć tutaj https://github.com/psharanda/Atributika

Pavel Sharanda
źródło
0

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

Lista atrybutów zobacz tutaj NSAttortedStringKey w Apple Docs

Shan Ye
źródło
0

Bardzo łatwy sposób to zrobić.

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

Aby uzyskać więcej informacji kliknij tutaj; https://github.com/iOSTechHub/AttributString

Ashish Chauhan
źródło