IOS

IOS TutorialAirPrint tutorial in iOSCarthage iOS SetupChecking iOS versionCore SpotLight in iOSCreate a Custom framework in iOSDeep Linking in iOSExtension for rich Push Notification - iOS 10.Guideline to choose best iOS Architecture PatternsIOS - Implementation of XMPP with Robbie Hanson frameworkIOS 3D TouchIOS 10 Speech Recognition APIIOS AccessibilityIOS ADDING a SWIFT BRIDGING HEADERIOS AFNetworkingIOS AirDropIOS AlamofireIOS App Submission ProcessIOS App Transport Security (ATS)IOS App wide operationsIOS AppDelegateIOS Application rating/review requestIOS ARC (Automatic Reference Counting)IOS attributedText in UILabelIOS Auto LayoutIOS AVPlayer and AVPlayerViewControllerIOS AVSpeechSynthesizerIOS AWS SDKIOS Background ModesIOS Background Modes and EventsIOS Basic text file I/OIOS BlockIOS CAAnimationIOS Cache online imagesIOS CAGradientLayerIOS CALayerIOS CAShapeLayerIOS CategoriesIOS CGContext ReferenceIOS Chain Blocks in a Queue (with MKBlockQueue)IOS Change Status Bar ColorIOS Checking for Network ConnectivityIOS CLLocationIOS CloudKitIOS CodableIOS Code signingIOS ConcurrencyIOS Configure Beacons with CoreBluetoothIOS Contacts FrameworkIOS Content Hugging/Content Compression in AutoLayoutIOS Convert HTML to NSAttributed string and vice verseIOS Convert NSAttributedString to UIImageIOS Core DataIOS Core GraphicsIOS Core LocationIOS Core MotionIOS CoreImage FiltersIOS Create .ipa File to upload on appstore with ApplicationloaderIOS Create a video from imagesIOS Creating an App IDIOS CTCallCenterIOS Custom fontsIOS Custom KeyboardIOS Custom methods of selection of UITableViewCellsIOS Custom UITextFieldIOS Custom UIViews from XIB filesIOS Cut a UIImage into a circleIOS CydiaSubstrate tweakIOS Debugging CrashesIOS DispatchGroupIOS Dynamic TypeIOS Dynamically updating a UIStackViewIOS EventKitIOS Face Detection Using CoreImage/OpenCVIOS FacebookSDKIOS FastlaneIOS FCM Messaging in SwiftIOS FileHandleIOS GameCenter LeaderboardsIOS GameplayKitIOS GCD (Grand Central Dispatch)IOS Google Places APIIOS Graph (Coreplot)IOS Handle Multiple Environment using MacroIOS Handling URL SchemesIOS HealthkitIOS iBeaconIOS IBOutletsIOS In-App PurchaseIOS Initialization idioms



IOS NSAttributedString

From WikiOD

Remarks[edit | edit source]

Set Color of Font Using NSAttributedString

Creating a string that has custom kerning (letter spacing)[edit | edit source]

NSAttributedString (and its mutable sibling NSMutableAttributedString) allows you to create strings that are complex in their appearance to the user.

A common application is to use this to display a string and adding custom kerning / letter-spacing.

This would be achieved as follows (where label is a UILabel), giving a different kerning for the word "kerning"

Swift

var attributedString = NSMutableAttributedString("Apply kerning")
attributedString.addAttribute(attribute: NSKernAttributeName, value: 5, range: NSMakeRange(6, 7))
label.attributedText = attributedString

Objective-C

NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Apply kerning"];
[attributedString addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(6, 7)];
[label setAttributedText:attributedString];

Change the color of a word or string[edit | edit source]

Objective-C

UIColor *color = [UIColor redColor];
NSString *textToFind = @"redword";

NSMutableAttributedString *attrsString =  [[NSMutableAttributedString alloc] initWithAttributedString:yourLabel.attributedText];

// search for word occurrence
NSRange range = [yourLabel.text rangeOfString:textToFind];
if (range.location != NSNotFound) {
    [attrsString addAttribute:NSForegroundColorAttributeName value:color range:range];
}

// set attributed text
yourLabel.attributedText = attrsString;

Swift

let color = UIColor.red;
let textToFind = "redword"

let attrsString =  NSMutableAttributedString(string:yourlabel.text!);

// search for word occurrence
let range = (yourlabel.text! as NSString).range(of: textToFind)
if (range.length > 0) {
     attrsString.addAttribute(NSForegroundColorAttributeName,value:color,range:range)
}

// set attributed text
yourlabel.attributedText = attrsString

Note:

The main here is to use a NSMutableAttributedString and the selector addAttribute:value:range with the attribute NSForegroundColorAttributeName to change a color of a string range:

NSMutableAttributedString *attrsString =  [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
[attrsString addAttribute:NSForegroundColorAttributeName value:color range:range];

You could use another way to get the range, for example: NSRegularExpression.

Create a string with strikethrough text[edit | edit source]

Objective-C

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
                    value:@2
                    range:NSMakeRange(0, [attributeString length])];

Swift

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your String here")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

Then you can add this to your UILabel:

yourLabel.attributedText = attributeString;

Appending Attributed Strings and bold text in Swift[edit | edit source]

let someValue : String = "Something the user entered"     
let text = NSMutableAttributedString(string: "The value is: ")
text.appendAttributedString(NSAttributedString(string: someValue, attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(UIFont.systemFontSize())]))

The result looks like:

The value is: Something the user entered

Removing all attributes[edit | edit source]

Objective-C

NSMutableAttributedString *mutAttString = @"string goes here";
NSRange range = NSMakeRange(0, mutAttString.length);
[mutAttString setAttributes:@{} range:originalRange];

As per Apple Documentation we use, setAttributes and not addAttribute.

Swift

mutAttString.setAttributes([:], range: NSRange(0..<string.length))

Credit:Stack_Overflow_Documentation