Change the color of a link in an NSMutableAttributedString

Swift Updated for Swift 4.2 Use linkTextAttributes with a UITextView textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green] And in context: let attributedString = NSMutableAttributedString(string: “The site is www.google.com.”) let linkRange = (attributedString.string as NSString).range(of: “www.google.com”) attributedString.addAttribute(NSAttributedString.Key.link, value: “https://www.google.com”, range: linkRange) let linkAttributes: [NSAttributedString.Key : Any] = [ NSAttributedString.Key.foregroundColor: UIColor.green, NSAttributedString.Key.underlineColor: UIColor.lightGray, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ] // textView is a … Read more

Color all occurrences of string in swift

Swift 5 let attrStr = NSMutableAttributedString(string: “hi hihi hey”) let inputLength = attrStr.string.count let searchString = “hi” let searchLength = searchString.characters.count var range = NSRange(location: 0, length: attrStr.length) while (range.location != NSNotFound) { range = (attrStr.string as NSString).range(of: searchString, options: [], range: range) if (range.location != NSNotFound) { attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.yellow, range: NSRange(location: range.location, length: … Read more

Changing specific text’s color using NSMutableAttributedString in Swift

let mainString = “Hello World” let stringToColor = “World” SWIFT 5 let range = (mainString as NSString).range(of: stringToColor) let mutableAttributedString = NSMutableAttributedString.init(string: mainString) mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range) textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100)) textField.attributedText = mutableAttributedString SWIFT 4.2 let range = (mainString as NSString).range(of: stringToColor) let mutableAttributedString = NSMutableAttributedString.init(string: mainString) mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: … Read more

Making text bold using attributed string in swift

Usage: let label = UILabel() label.attributedText = NSMutableAttributedString() .bold(“Address: “) .normal(” Kathmandu, Nepal\n\n”) .orangeHighlight(” Email: “) .blackHighlight(” [email protected] “) .bold(“\n\nCopyright: “) .underlined(” All rights reserved. 2020.”) Result: Here is a neat way to make a combination of bold and normal texts in a single label plus some other bonus methods. Extension: Swift 5.* extension NSMutableAttributedString … Read more