Swift IOS: Highlight specific character in Text - range

I working with highlighting of particular character in a given text.
Here is my worked code,
let titleLabel: UILabel!
let myText = "கொக்கு"
let textToHighlight = "க்"
titleLabel.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let textStroke: [NSAttributedString.Key : Any] = [
.strokeColor : UIColor.white,
.foregroundColor : UIColor.red,
.strokeWidth : -2.0,
]
let textTitle = NSMutableAttributedString(string: myText)
let textHighlightRange = (myText as NSString).range(of: textToHighlight)
textTitle.addAttributes(textStroke, range: textHighlightRange)
titleLabel.attributedText = textTitle
The other Texts which i worked and getting the expected results, but only few words specific in tamil languages am facing issues,
Other Languages Text working fine were,
let myText = "MyText"
let textToHighlight = "T"
let myText = "मानक हिन्दी"
let textToHighlight = "न"
Facing Issues with the text,
let myText = "கொக்கு"
let textToHighlight = "க்"
As i googled and got few details from the link
NSRange in Strings having dialects.
But how to find() and advance() methods used in the given reference.
I am using xcode 11.2 and swift version 4
EDIT:
After a long time, i found a nearest solution to highlight / change foreground color of my matched character in the text as below,
func characterToHighlight(text: String, highlight: String) -> NSAttributedString? {
guard let match = try? NSRegularExpression(pattern: highlight, options: .caseInsensitive) else {
return nil
}
let textStroke: [NSAttributedString.Key : Any] = [
.strokeColor : UIColor.white,
.foregroundColor : UIColor.red,
.strokeWidth : -2.0,
]
let attributedString = NSMutableAttributedString(string: text)
match
.matches(in: text, options: .withTransparentBounds,
range: NSRange(location: 0, length: text.utf16.count))
.forEach {
attributedString.addAttributes(textStroke, range: $0.range)
}
return attributedString
}
if let matchedCharacter = characterToHighlight(text: text, highlight: textToHighlight){titleLabel.attributedText = matchedCharacter}
This code works for the matched character of tamil letters in the string but the foreground of the other letters were black.
I need the non-matched characters in blue color and the matched characters in red color.
How to achieve this?
ANSWER:
let titleLabel: UILabel!
let myText = "கொக்கு"
let textToHighlight = "க்"
titleLabel.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let textStroke: [NSAttributedString.Key : Any] = [
.strokeColor : UIColor.white,
.foregroundColor : UIColor.blue,
.strokeWidth : -2.0,
]
let highlightTextAttributes: [NSAttributedString.Key : Any] = [
.strokeColor : UIColor.white,
.foregroundColor : UIColor.red,
.strokeWidth : -4.0,
]
let textTitle = NSMutableAttributedString(string: myText)
textTitle.addAttributes(textStroke, range: textHighlightRange)
if let matchedCharacterRange = getRange(text: text, highlight: textToHighlight)
{
textTitle.addAttributes(highlightTextAttributes, range: matchedCharacterRange)
}
titleLabel.attributedText = textTitle
func getRange(text: String, highlight: String) -> NSRange? {
guard let regex = try? NSRegularExpression(pattern: highlight, options: .caseInsensitive) else {
return nil
}
var highlightRange: NSRange?
regex
.matches(in: text, options: .withTransparentBounds,
range: NSRange(location: 0, length: text.utf16.count))
.forEach {
highlightRange = $0.range
}
return highlightRange
}
I am unable to post my answer separately, so i am editing my question and posting the answer in the same.
Experts, please review and correct me if am wrong.
Thanks for your support.

Related

Change word colour from sentence with regex

I have sentence "This is my first test", I need to change for example word "first" to another colour. But this sentences will come from backend. So,i need maybe with regex take word from sentence, and back it with another colour.
How to back this word into sentence, or maybe better way to change colour of word from sentence?
var string = "This is my text=\"first\" test!"
let pattern = ".*(?=( - text=\"[\\w\\s]+\"))|(?<=text=\")([\\w\\s]+)"
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
for match in matches {
if let range = Range(match.range, in: string) {
let name = string[range]
if let range = string.range(of: "text=\"\(name)\"") {
string.removeSubrange(range)
debugPrint("WORD CHANGE COLOR: \(name)") // first
debugPrint("PHRASE IS: \(string)") // This is my test!
}
let attrs1 = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.black]
let attributedString1 = NSMutableAttributedString(string: String(name),attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string: self.phrase, attributes: attrs2)
titleLabel.attributedText = attributedString1
// titleLabel.attributedText = attributedString2
}
}
} catch {
print("Regex was bad!")
}
Here's a working solution (with extra initial values to be usable in Playgrounds).
What's the idea:
Work directly on a NS(Mutable)AttributedString.
Change the regex pattern, to let you know what's the real full range, what's the range of "first".
Enumerate the matches in reverse (because you'll be modifying the string, so the ranges won't be valid afterwards, since replacement won't have the same length)
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
titleLabel.backgroundColor = .blue
let string = "This is my text=\"first\" test!"
let attributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20), NSAttributedString.Key.foregroundColor : UIColor.black])
let pattern = "text=\"([\\w\\s]+)\""
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: attributedString.string, options: [], range: NSRange(location: 0, length: attributedString.length))
for match in matches.reversed() {
let globalNSRange = match.range
let worldNSRange = match.range(at: 1)
let replacement = NSMutableAttributedString(attributedString: attributedString.attributedSubstring(from: worldNSRange))
replacement.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor : UIColor.green],
range: NSRange(location: 0, length: replacement.length))
attributedString.replaceCharacters(in: globalNSRange, with: replacement)
}
titleLabel.attributedText = attributedString
} catch {
print("Regex was bad: \(error)") //Print useful information on why it failed, like the actual thrown error
}
return titleLabel

Customise embedded hyperlink in UITextView using Swift iOS13

Since installing iOS13 the UITextView extension is only customizing the background (to white color) around the text itself and not the entire UITextView.
How can I make sure that the entire UITextview object's background color is changed to white?
Extention:
extension UITextView {
func hyperLink(originalText: String, hyperLink: String, urlString: String) {
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.white, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 11), range: fullRange)
self.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.black,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue,
] as [NSAttributedString.Key : Any]
self.attributedText = attributedOriginalText
}//end func
}
Usage:
class LoginVC: UIViewController {
#IBOutlet weak var disclaimerTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
disclaimerTextView.hyperLink(originalText: "By continuing, you agree to our Terms and Privacy Policy found on our website", hyperLink: "website", urlString: WEBSITE_URL)
}
}
EDIT: output of the suggested solution - not working.
Changing the extension to this:
extension UITextView {
func hyperLink(originalText: String, hyperLink: String, urlString: String) {
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 11), range: fullRange)
self.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.black,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue,
] as [NSAttributedString.Key : Any]
self.attributedText = attributedOriginalText
}
}
Is working for me. I simply removed the attributed text attributes that changed the foreground and background colors. I'm not sure why they were there to begin with.

UITextView with hyperlink text

With a non-editable UITextView, I would like to embed text like this in iOS9+:
Just click here to register
I can create a function and manipulate the text but is there a simpler way?
I see that I can use NSTextCheckingTypeLink so getting the text clickable without the 'click here' part is straightforward in Interface Builder:
Just http://example.com to register
I'm using Xcode 8 and Swift 3 if that's relevant.
Set isEditable = false or the text view will go into text-editing mode when user taps on it.
Swift 4 and later
let attributedString = NSMutableAttributedString(string: "Just click here to register")
let url = URL(string: "https://www.apple.com")!
// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))
self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false
// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
If you want to use multiple hyperlinks you can use this alternative for Swift 5
extension UITextView {
func addHyperLinksToText(originalText: String, hyperLinks: [String: String]) {
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
for (hyperLink, urlString) in hyperLinks {
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: YourFont, range: fullRange)
}
self.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: YourColor,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
]
self.attributedText = attributedOriginalText
}
}
Usage:
yourTextView.addHyperLinksToText(originalText: "Testing hyperlinks here and there", hyperLinks: ["here": "someUrl1", "there": "someUrl2"])
The same solution for Swift 3 using extensions :
A. Add extension -
extension UITextView {
func hyperLink(originalText: String, hyperLink: String, urlString: String) {
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSLinkAttributeName, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSParagraphStyleAttributeName, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 10), range: fullRange)
self.linkTextAttributes = [
NSForegroundColorAttributeName: UIConfig.primaryColour,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
]
self.attributedText = attributedOriginalText
}
}
B. Add link url - let linkUrl = "https://www.my_website.com"
C. Implement UITextViewDelegate in your ViewController like this -
class MyViewController: UIViewController, UITextViewDelegate {
}
D. Add delegate method to handle tap events -
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == linkUrl) {
UIApplication.shared.openURL(URL)
}
return false
}
}
E. And finally, things to make sure for your UITextView under attribute inspector -
Behaviour - Editable is turned OFF & Selectable is turned ON.
Data Detectors - Link is turned ON.
Usage -
textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)
Cheers & happy coding!
Swift 5
This is based on Tejas' answer as a few items in both classes were deprecated.
extension UITextView {
func hyperLink(originalText: String, hyperLink: String, urlString: String) {
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)
self.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.blue,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue,
] as [NSAttributedString.Key : Any]
self.attributedText = attributedOriginalText
}
Don't forget to add UITextViewDelegate to your view controller and set your let linkUrl = "https://example.com"
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == linkUrl) {
UIApplication.shared.open(URL) { (Bool) in
}
}
return false
}
Usage stays the same:
textView.hyperLink(originalText: "To find out more please visit our website", hyperLink: "website", urlString: linkUrl)
Swift 4 code.
May be I'm the only one who needs to set several links and color the words in one message. I created an AttribTextHolder class to accumulate all information about text inside this holder and easily pass it between objects to set text to UITextView somewhere deep inside a controller.
class AttribTextHolder {
enum AttrType {
case link
case color
}
let originalText: String
var attributes: [(text: String, type: AttrType, value: Any)]
init(text: String, attrs: [(text: String, type: AttrType, value: Any)] = [])
{
originalText = text
attributes = attrs
}
func addAttr(_ attr: (text: String, type: AttrType, value: Any)) -> AttribTextHolder {
attributes.append(attr)
return self
}
func setTo(textView: UITextView)
{
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
for item in attributes {
let arange = attributedOriginalText.mutableString.range(of: item.text)
switch item.type {
case .link:
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: item.value, range: arange)
case .color:
var color = UIColor.black
if let c = item.value as? UIColor { color = c }
else if let s = item.value as? String { color = s.color() }
attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: arange)
default:
break
}
}
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
textView.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.blue,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
] as [String : Any]
textView.attributedText = attributedOriginalText
}
}
Use it like this:
let txt = AttribTextHolder(text: "To find out more visit our website or email us your questions")
.addAttr((text: "our website", type: .link, "http://example.com"))
.addAttr((text: "our website", type: .color, "#33BB22"))
.addAttr((text: "email us", type: .link, "mailto:us#example.com"))
.addAttr((text: "email us", type: .color, UIColor.red))
....
....
txt.setTo(textView: myUITextView)
Also in this code I use simple String extension to convert String hex values into UIColor objects
extension String {
/// Converts string color (ex: #23FF33) into UIColor
func color() -> UIColor {
let hex = self.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
Using Swift >= 4:
let descriptionText = NSMutableAttributedString(string:"To learn more, check out our ", attributes: [:])
let linkText = NSMutableAttributedString(string: "Privacy Policy and Terms of Use", attributes: [NSAttributedString.Key.link: URL(string: example.com)!])
descriptionText.append(linkText)
The same solution for Swift 4 using extensions:
extension UITextView {
func hyperLink(originalText: String, hyperLink: String, urlString: String) {
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedStringKey.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)
self.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.blue,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
] as [String : Any]
self.attributedText = attributedOriginalText
}
}
A safer solution to implement hyperlink via UITextView
var termsConditionsTextView: UITextView = {
let view = UITextView()
view.backgroundColor = .clear
view.textAlignment = .left
let firstTitleString = "By registering for THIS_APP I agree with the "
let secondTitleString = "Terms & Conditions"
let finishTitleString = firstTitleString + secondTitleString
let attributedString = NSMutableAttributedString(string: finishTitleString)
attributedString.addAttribute(.link, value: "https://stackoverflow.com", range: NSRange(location: firstTitleString.count, length: secondTitleString.count))
view.attributedText = attributedString
view.textContainerInset = .zero
view.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.isEmpty
]
view.font = view.font = UIFont(name: "YOUR_FONT_NAME", size: 16)
view.textColor = UIColor.black
return view }()
SWIFT 5 AND MORE THAN ONE LINK
import UIKit
public extension UITextView {
func hyperLink(originalText: String, linkTextsAndTypes: [String: String]) {
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
for linkTextAndType in linkTextsAndTypes {
let linkRange = attributedOriginalText.mutableString.range(of: linkTextAndType.key)
let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: linkTextAndType.value, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 10), range: fullRange)
}
self.linkTextAttributes = [
kCTForegroundColorAttributeName: UIColor.blue,
kCTUnderlineStyleAttributeName: NSUnderlineStyle.single.rawValue
] as [NSAttributedString.Key: Any]
self.attributedText = attributedOriginalText
}
}
And the usage in your viewController:
#IBOutlet weak var termsHyperlinkTextView: UITextView! {
didSet {
termsHyperlinkTextView.delegate = self
termsHyperlinkTextView.hyperLink(originalText: "Check out terms & conditions or our privacy policy",
linkTextsAndTypes: ["terms & conditions": LinkType.termsAndConditions.rawValue,
"privacy policy": LinkType.privacyPolicy.rawValue])
}
}
enum LinkType: String {
case termsAndConditions
case privacyPolicy
}
// MARK: - UITextViewDelegate
extension ViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if let linkType = LinkType(rawValue: URL.absoluteString) {
// TODO: handle linktype here with switch or similar.
}
return false
}
}
You could use this simple method to add a hyperlink to any set of characters starting with tag
func addLink(forString string : NSMutableAttributedString
,baseURL : String
,tag : String){
let array = string.string.replacingOccurrences(of: "\n", with: " ").components(separatedBy: " ")
let filterArray = array.filter { (string) -> Bool in
return string.contains(tag)
}
for element in filterArray {
let removedHashtag = element.replacingOccurrences(of: tag, with: "")
let url = baseURL + removedHashtag
let range = NSString.init(string: (string.string)).range(of: element)
string.addAttributes([NSAttributedStringKey.link : url.replacingOccurrences(of: " ", with: "")], range: range)
}
}
I wanted to do the same thing and ended up just using a UIButton with the title "click here" surrounded by UILabels "just " and " to register", and then:
#IBAction func btnJustClickHereLink(_ sender: UIButton) {
if let url = URL(string: "http://example.com") {
UIApplication.shared.openURL(url)
}
}

Swift Text Attributes Color [duplicate]

The issue I am having is that I want to be able to change the textColor of certain text in a TextView. I am using a concatenated string, and just want the strings I am appending into the TextView's text. It appears that what I want to use is NSMutableAttributedString, but I am not finding any resources of how to use this in Swift. What I have so far is something like this:
let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
From here I know I need to find the range of words that need to have their textColor changed and then add them to the attributed string. What I need to know is how to find the correct strings from the attributedString, and then change their textColor.
Since I have too low of a rating I can't answer my own question, but here is the answer I found
I found my own answer by translating from translating some code from
Change attributes of substrings in a NSAttributedString
Here is the example of implementation in Swift:
let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)
let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
let wordRange = stringOneMatch.rangeAtIndex(0)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}
textView.attributedText = attributedString
Since I am wanting to change the textColor of multiple Strings I will make a helper function to handle this, but this works for changing the textColor.
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: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
I see you have answered the question somewhat, but to provide a slightly more concise way without using regex to answer to the title question:
To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.
var main_string = "Hello World"
var string_to_color = "World"
var range = (main_string as NSString).rangeOfString(string_to_color)
Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:
var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
A list of further standard attributes you can set can be found in Apple's documentation
Swift 2.1 Update:
let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
let linkTextWithColor = "click here"
let range = (text as NSString).rangeOfString(linkTextWithColor)
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
self.helpText.attributedText = attributedString
self.helpText is a UILabel outlet.
Swift 4.2 and Swift 5 colorise parts of the string.
A very easy way to use NSMutableAttributedString while extending the String. This also can be used to colourize more than one word in the whole string.
import UIKit
extension String {
func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for string in strings {
let range = (self as NSString).range(of: string)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
guard let characterSpacing = characterSpacing else {return attributedString}
attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
return attributedString
}
}
Now you can use globally at any viewcontroller you want:
let attributedWithTextColor: NSAttributedString = "Doc, welcome back :)".attributedStringWithColor(["Doc", "back"], color: UIColor.black)
myLabel.attributedText = attributedWithTextColor
Answer is already given in previous posts but i have a different way of doing this
Swift 3x :
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: "Your full label textString")
myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
, NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give
yourLabel.attributedText = myMutableString
Hope this helps anybody!
Chris' answer was a great help to me, so I used his approach and turned into a func that I can reuse. This let's me assign a color to a substring while giving the rest of the string another color.
static func createAttributedString(fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) -> NSMutableAttributedString
{
let range = (fullString as NSString).rangeOfString(subString)
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.addAttribute(NSForegroundColorAttributeName, value: fullStringColor, range: NSRange(location: 0, length: fullString.characters.count))
attributedString.addAttribute(NSForegroundColorAttributeName, value: subStringColor, range: range)
return attributedString
}
Swift 4.1
NSAttributedStringKey.foregroundColor
for example if you want to change font in NavBar:
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]
You can use this extension
I test it over
swift 4.2
import Foundation
import UIKit
extension NSMutableAttributedString {
convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
let rangeOfSubString = (fullString as NSString).range(of: subString)
let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)
self.init(attributedString: attributedString)
}
}
Swift 2.2
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: "1234567890", attributes: [NSFontAttributeName:UIFont(name: kDefaultFontName, size: 14.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0/255.0, green: 125.0/255.0, blue: 179.0/255.0, alpha: 1.0), range: NSRange(location:0,length:5))
self.lblPhone.attributedText = myMutableString
Easiest way to do label with different style such as color, font etc. is use property "Attributed" in Attributes Inspector. Just choose part of text and change it like you want
Based on the answers before I created a string extension
extension String {
func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
let range = (self as NSString).range(of: highlightedWords)
let result = NSMutableAttributedString(string: self)
for attribute in attributes {
result.addAttributes(attribute, range: range)
}
return result
}
}
You can pass the attributes for the text to the method
Call like this
let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)
Swift 4.1
I have changed from this
In Swift 3
let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
And this in Swift 4.0
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
to Swift 4.1
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
Works fine
swift 4.2
let textString = "Hello world"
let range = (textString as NSString).range(of: "world")
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
self.textUIlable.attributedText = attributedString
This might be work for you
let main_string = " User not found,Want to review ? Click here"
let string_to_color = "Click here"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue , range: range)
lblClickHere.attributedText = attribute
With this simple function you can assign the text and highlight the chosen word.
You can also change the UITextView to UILabel, etc.
func highlightBoldWordAtLabel(textViewTotransform: UITextView, completeText: String, wordToBold: String){
textViewToTransform.text = completeText
let range = (completeText as NSString).range(of: wordToBold)
let attribute = NSMutableAttributedString.init(string: completeText)
attribute.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 16), range: range)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)
textViewToTransform.attributedText = attribute
}
For everyone who are looking for "Applying specific color to multiple words in text", we can do it using NSRegularExpression
func highlight(matchingText: String, in text: String) {
let attributedString = NSMutableAttributedString(string: text)
if let regularExpression = try? NSRegularExpression(pattern: "\(matchingText)", options: .caseInsensitive) {
let matchedResults = regularExpression.matches(in: text, options: [], range: NSRange(location: 0, length: attributedString.length))
for matched in matchedResults {
attributedString.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: matched.range)
}
yourLabel.attributedText = attributedString
}
}
Reference link : https://gist.github.com/aquajach/4d9398b95a748fd37e88
You can use as simple extension
extension String{
func attributedString(subStr: String) -> NSMutableAttributedString{
let range = (self as NSString).range(of: subStr)
let attributedString = NSMutableAttributedString(string:self)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
return attributedString
}
}
myLable.attributedText = fullStr.attributedString(subStr: strToChange)
This extension works well when configuring the text of a label with an already set default color.
public extension String {
func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
let range = (self as NSString).range(of: substring)
let attributedString = NSMutableAttributedString(string: self)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
return attributedString
}
}
For example
let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")
let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText
Super easy way to do this.
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))
For more detail click here:
https://github.com/iOSTechHub/AttributedString
To change color of the font colour, first select attributed instead of plain like in the image below
You then need to select the text in the attributed field and then select the color button on the right-hand side of the alignments. This will change the color.
You can use this method. I implemented this method in my common utility class to access globally.
func attributedString(with highlightString: String, normalString: String, highlightColor: UIColor) -> NSMutableAttributedString {
let attributes = [NSAttributedString.Key.foregroundColor: highlightColor]
let attributedString = NSMutableAttributedString(string: highlightString, attributes: attributes)
attributedString.append(NSAttributedString(string: normalString))
return attributedString
}
If you are using Swift 3x and UITextView, maybe the NSForegroundColorAttributeName won't work (it didn't work for me no matter what approach I tried).
So, after some digging around I found a solution.
//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red
You need to change textview parameters, not parameters of attributed string
textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.underlineColor: UIColor.red,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
Please check cocoapod Prestyler:
Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()
extension String{
// to make text field mandatory * looks
mutating func markAsMandatoryField()-> NSAttributedString{
let main_string = self
let string_to_color = "*"
let range = (main_string as NSString).range(of: string_to_color)
print("The rang = \(range)")
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.rgbColor(red: 255.0, green: 0.0, blue: 23.0) , range: range)
return attribute
}
}
use
EmailLbl.attributedText = EmailLbl.text!.markAsMandatoryField()

Is there a simple way to make text in a variable bold in Swift? [duplicate]

I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.
I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.
var coffeeAmount: String = calculatedCoffee + attributedText
Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create. Maybe I'm going about this the wrong way. Any help is appreciated!
This answer has been updated for Swift 4.2.
Quick Reference
The general form for making and setting an attributed string is like this. You can find other common options below.
// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
// set attributed text on a UILabel
myLabel.attributedText = myAttrString
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]
The rest of this post gives more detail for those who are interested.
Attributes
String attributes are just a dictionary in the form of [NSAttributedString.Key: Any], where NSAttributedString.Key is the key name of the attribute and Any is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:
key name: NSAttributedString.Key.font, value: a UIFont
key name: NSAttributedString.Key.foregroundColor, value: a UIColor
key name: NSAttributedString.Key.link, value: an NSURL or NSString
There are many others. See this link for more. You can even make your own custom attributes like:
key name: NSAttributedString.Key.myName, value: some Type.
if you make an extension:
extension NSAttributedString.Key {
static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
}
Creating attributes in Swift
You can declare attributes just like declaring any other dictionary.
// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.backgroundColor: UIColor.yellow,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]
// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]
Note the rawValue that was needed for the underline style value.
Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use Any as the type. Here is the multipleAttributes example from above, recreated in this fashion:
var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue
Attributed Strings
Now that you understand attributes, you can make attributed strings.
Initialization
There are a few ways to create attributed strings. If you just need a read-only string you can use NSAttributedString. Here are some ways to initialize it:
// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)
If you will need to change the attributes or the string content later, you should use NSMutableAttributedString. The declarations are very similar:
// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()
// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")
// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])
// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)
Changing an Attributed String
As an example, let's create the attributed string at the top of this post.
First create an NSMutableAttributedString with a new font attribute.
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )
If you are working along, set the attributed string to a UITextView (or UILabel) like this:
textView.attributedText = myString
You don't use textView.text.
Here is the result:
Then append another attributed string that doesn't have any attributes set. (Notice that even though I used let to declare myString above, I can still modify it because it is an NSMutableAttributedString. This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.)
let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)
Next we'll just select the "Strings" word, which starts at index 17 and has a length of 7. Notice that this is an NSRange and not a Swift Range. (See this answer for more about Ranges.) The addAttribute method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot.
var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)
Finally, let's add a background color. For variety, let's use the addAttributes method (note the s). I could add multiple attributes at once with this method, but I will just add one again.
myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)
Notice that the attributes are overlapping in some places. Adding an attribute doesn't overwrite an attribute that is already there.
Related
How to change the text of an NSMutableAttributedString but keep the attributes
Further Reading
How to retrieve the attributes from a tap location
Attributed String Programming Guide (very informative but unfortunately only in Objective-C)
Swift uses the same NSMutableAttributedString that Obj-C does. You instantiate it by passing in the calculated value as a string:
var attributedString = NSMutableAttributedString(string:"\(calculatedCoffee)")
Now create the attributed g string (heh). Note: UIFont.systemFontOfSize(_) is now a failable initializer, so it has to be unwrapped before you can use it:
var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(19.0)!]
var gString = NSMutableAttributedString(string:"g", attributes:attrs)
And then append it:
attributedString.appendAttributedString(gString)
You can then set the UILabel to display the NSAttributedString like this:
myLabel.attributedText = attributedString
I would highly recommend using a library for attributed strings. It makes it much easier when you want, for example, one string with four different colors and four different fonts. Here is my favorite. It is called SwiftyAttributes
If you wanted to make a string with four different colors and different fonts using SwiftyAttributes:
let magenta = "Hello ".withAttributes([
.textColor(.magenta),
.font(.systemFont(ofSize: 15.0))
])
let cyan = "Sir ".withAttributes([
.textColor(.cyan),
.font(.boldSystemFont(ofSize: 15.0))
])
let green = "Lancelot".withAttributes([
.textColor(.green),
.font(.italicSystemFont(ofSize: 15.0))
])
let blue = "!".withAttributes([
.textColor(.blue),
.font(.preferredFont(forTextStyle: UIFontTextStyle.headline))
])
let finalString = magenta + cyan + green + blue
finalString would show as
Xcode 6 version:
let attriString = NSAttributedString(string:"attriString", attributes:
[NSForegroundColorAttributeName: UIColor.lightGrayColor(),
NSFontAttributeName: AttriFont])
Xcode 9.3 version:
let attriString = NSAttributedString(string:"attriString", attributes:
[NSAttributedStringKey.foregroundColor: UIColor.lightGray,
NSAttributedStringKey.font: AttriFont])
Xcode 10, iOS 12, Swift 4:
let attriString = NSAttributedString(string:"attriString", attributes:
[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
NSAttributedString.Key.font: AttriFont])
Swift 4:
let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
NSAttributedStringKey.foregroundColor: UIColor.white]
Swift 5
let attrStri = NSMutableAttributedString.init(string:"This is red")
let nsRange = NSString(string: "This is red")
.range(of: "red", options: String.CompareOptions.caseInsensitive)
attrStri.addAttributes([
NSAttributedString.Key.foregroundColor : UIColor.red,
NSAttributedString.Key.font: UIFont.init(name: "PTSans-Regular", size: 15.0) as Any
], range: nsRange)
self.label.attributedText = attrStri
Swift: xcode 6.1
let font:UIFont? = UIFont(name: "Arial", size: 12.0)
let attrString = NSAttributedString(
string: titleData,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName))
Details
Swift 5.2, Xcode 11.4 (11E146)
Solution
protocol AttributedStringComponent {
var text: String { get }
func getAttributes() -> [NSAttributedString.Key: Any]?
}
// MARK: String extensions
extension String: AttributedStringComponent {
var text: String { self }
func getAttributes() -> [NSAttributedString.Key: Any]? { return nil }
}
extension String {
func toAttributed(with attributes: [NSAttributedString.Key: Any]?) -> NSAttributedString {
.init(string: self, attributes: attributes)
}
}
// MARK: NSAttributedString extensions
extension NSAttributedString: AttributedStringComponent {
var text: String { string }
func getAttributes() -> [Key: Any]? {
if string.isEmpty { return nil }
var range = NSRange(location: 0, length: string.count)
return attributes(at: 0, effectiveRange: &range)
}
}
extension NSAttributedString {
convenience init?(from attributedStringComponents: [AttributedStringComponent],
defaultAttributes: [NSAttributedString.Key: Any],
joinedSeparator: String = " ") {
switch attributedStringComponents.count {
case 0: return nil
default:
var joinedString = ""
typealias SttributedStringComponentDescriptor = ([NSAttributedString.Key: Any], NSRange)
let sttributedStringComponents = attributedStringComponents.enumerated().flatMap { (index, component) -> [SttributedStringComponentDescriptor] in
var components = [SttributedStringComponentDescriptor]()
if index != 0 {
components.append((defaultAttributes,
NSRange(location: joinedString.count, length: joinedSeparator.count)))
joinedString += joinedSeparator
}
components.append((component.getAttributes() ?? defaultAttributes,
NSRange(location: joinedString.count, length: component.text.count)))
joinedString += component.text
return components
}
let attributedString = NSMutableAttributedString(string: joinedString)
sttributedStringComponents.forEach { attributedString.addAttributes($0, range: $1) }
self.init(attributedString: attributedString)
}
}
}
Usage
let defaultAttributes = [
.font: UIFont.systemFont(ofSize: 16, weight: .regular),
.foregroundColor: UIColor.blue
] as [NSAttributedString.Key : Any]
let marketingAttributes = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
.foregroundColor: UIColor.black
] as [NSAttributedString.Key : Any]
let attributedStringComponents = [
"pay for",
NSAttributedString(string: "one",
attributes: marketingAttributes),
"and get",
"three!\n".toAttributed(with: marketingAttributes),
"Only today!".toAttributed(with: [
.font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
.foregroundColor: UIColor.red
])
] as [AttributedStringComponent]
let attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)
Full Example
do not forget to paste the solution code here
import UIKit
class ViewController: UIViewController {
private weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: .init(x: 40, y: 40, width: 300, height: 80))
label.numberOfLines = 2
view.addSubview(label)
self.label = label
let defaultAttributes = [
.font: UIFont.systemFont(ofSize: 16, weight: .regular),
.foregroundColor: UIColor.blue
] as [NSAttributedString.Key : Any]
let marketingAttributes = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
.foregroundColor: UIColor.black
] as [NSAttributedString.Key : Any]
let attributedStringComponents = [
"pay for",
NSAttributedString(string: "one",
attributes: marketingAttributes),
"and get",
"three!\n".toAttributed(with: marketingAttributes),
"Only today!".toAttributed(with: [
.font: UIFont.systemFont(ofSize: 16.0, weight: .bold),
.foregroundColor: UIColor.red
])
] as [AttributedStringComponent]
label.attributedText = NSAttributedString(from: attributedStringComponents, defaultAttributes: defaultAttributes)
label.textAlignment = .center
}
}
Result
The best way to approach Attributed Strings on iOS is by using the built-in Attributed Text editor in the interface builder and avoid uneccessary hardcoding NSAtrributedStringKeys in your source files.
You can later dynamically replace placehoderls at runtime by using this extension:
extension NSAttributedString {
func replacing(placeholder:String, with valueString:String) -> NSAttributedString {
if let range = self.string.range(of:placeholder) {
let nsRange = NSRange(range,in:valueString)
let mutableText = NSMutableAttributedString(attributedString: self)
mutableText.replaceCharacters(in: nsRange, with: valueString)
return mutableText as NSAttributedString
}
return self
}
}
Add a storyboard label with attributed text looking like this.
Then you simply update the value each time you need like this:
label.attributedText = initalAttributedString.replacing(placeholder: "<price>", with: newValue)
Make sure to save into initalAttributedString the original value.
You can better understand this approach by reading this article:
https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e
Swift 2.0
Here is a sample:
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString
Swift 5.x
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString
OR
let stringAttributes = [
NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 17.0)!,
NSUnderlineStyleAttributeName : 1,
NSForegroundColorAttributeName : UIColor.orangeColor(),
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
NSStrokeWidthAttributeName : 2.0]
let atrributedString = NSAttributedString(string: "Sample String: Attributed", attributes: stringAttributes)
sampleLabel.attributedText = atrributedString
I created an online tool that is going to solve your problem! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.
Also is open source so feel free to extend it and send PRs.
Transformer Tool
Github
Works well in beta 6
let attrString = NSAttributedString(
string: "title-title-title",
attributes: NSDictionary(
object: NSFont(name: "Arial", size: 12.0),
forKey: NSFontAttributeName))
Swift 5 and above
let attributedString = NSAttributedString(string:"targetString",
attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])
func decorateText(sub:String, des:String)->NSAttributedString{
let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.darkText, NSAttributedStringKey.font: UIFont(name: "PTSans-Bold", size: 17.0)!]
let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont(name: "PTSans-Regular", size: 14.0)!]
let textPartOne = NSMutableAttributedString(string: sub, attributes: textAttributesOne)
let textPartTwo = NSMutableAttributedString(string: des, attributes: textAttributesTwo)
let textCombination = NSMutableAttributedString()
textCombination.append(textPartOne)
textCombination.append(textPartTwo)
return textCombination
}
//Implementation
cell.lblFrom.attributedText = decorateText(sub: sender!, des: " - \(convertDateFormatShort3(myDateString: datetime!))")
Swift 4
let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
You need to remove the raw value in swift 4
Use this sample code. This is very short code to achieve your requirement. This is working for me.
let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
Swift 3,4,5
Use below code for Text Color, Font, Background Color and Underline/Un derline Color
let text = "swift is language"
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.backgroundColor: UIColor.blue,NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25.0),NSAttributedString.Key.underlineColor: UIColor.white,NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue] as [NSAttributedString.Key : Any]
let textAttribute = NSAttributedString(string: text, attributes: attributes)
swiftLabel1.attributedText = textAttribute
For me above solutions didn't work when setting a specific color or property.
This did work:
let attributes = [
NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 12.0)!,
NSUnderlineStyleAttributeName : 1,
NSForegroundColorAttributeName : UIColor.darkGrayColor(),
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
NSStrokeWidthAttributeName : 3.0]
var atriString = NSAttributedString(string: "My Attributed String", attributes: attributes)
Swift 2.1 - Xcode 7
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :[String:AnyObject] = [NSFontAttributeName : labelFont!]
let attrString = NSAttributedString(string:"foo", attributes: attributes)
myLabel.attributedText = attrString
I did a function that takes array of strings and returns attributed string with the attributes you give.
func createAttributedString(stringArray: [String], attributedPart: Int, attributes: [NSAttributedString.Key: Any]) -> NSMutableAttributedString? {
let finalString = NSMutableAttributedString()
for i in 0 ..< stringArray.count {
var attributedString = NSMutableAttributedString(string: stringArray[i], attributes: nil)
if i == attributedPart {
attributedString = NSMutableAttributedString(string: attributedString.string, attributes: attributes)
finalString.append(attributedString)
} else {
finalString.append(attributedString)
}
}
return finalString
}
In the example above you specify what part of string you want to get attributed with attributedPart: Int
And then you give the attributes for it with
attributes: [NSAttributedString.Key: Any]
USE EXAMPLE
if let attributedString = createAttributedString(stringArray: ["Hello ", "how ", " are you?"], attributedPart: 2, attributes: [NSAttributedString.Key.foregroundColor: UIColor.systemYellow]) {
myLabel.attributedText = attributedString
}
Will do:
extension UILabel{
func setSubTextColor(pSubString : String, pColor : UIColor){
let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);
let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
if range.location != NSNotFound {
attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
}
self.attributedText = attributedString
}
}
The attributes can be setting directly in swift 3...
let attributes = NSAttributedString(string: "String", attributes: [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 30)!,
NSForegroundColorAttributeName : UIColor .white,
NSTextEffectAttributeName : NSTextEffectLetterpressStyle])
Then use the variable in any class with attributes
Swift 4.2
extension UILabel {
func boldSubstring(_ substr: String) {
guard substr.isEmpty == false,
let text = attributedText,
let range = text.string.range(of: substr, options: .caseInsensitive) else {
return
}
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: self.font.pointSize)],
range: NSMakeRange(start, length))
attributedText = attr
}
}
It will be really easy to solve your problem with the library I created. It is called Atributika.
let calculatedCoffee: Int = 768
let g = Style("g").font(.boldSystemFont(ofSize: 12)).foregroundColor(.red)
let all = Style.font(.systemFont(ofSize: 12))
let str = "\(calculatedCoffee)<g>g</g>".style(tags: g)
.styleAll(all)
.attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
let attrString = NSAttributedString (
string: "title-title-title",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
Swifter Swift has a pretty sweet way to do this without any work really. Just provide the pattern that should be matched and what attributes to apply to it. They're great for a lot of things check them out.
``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``
If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.
You can do this in one step, just easier to read when separated.
Swift 4.x
let attr = [NSForegroundColorAttributeName:self.configuration.settingsColor, NSFontAttributeName: self.configuration.settingsFont]
let title = NSAttributedString(string: self.configuration.settingsTitle,
attributes: attr)
Swift 3.0
// create attributed string
Define attributes like
let attributes = [NSAttributedStringKey.font : UIFont.init(name: "Avenir-Medium", size: 13.0)]
Please consider using Prestyler
import Prestyler
...
Prestyle.defineRule("$", UIColor.red)
label.attributedText = "\(calculatedCoffee) $g$".prestyled()
Objective-C 2.0 example:
myUILabel.text = #"€ 60,00";
NSMutableAttributedString *amountText = [[NSMutableAttributedString alloc] initWithString:myUILabel.text];
//Add attributes you are looking for
NSDictionary *dictionaryOfAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:12],NSFontAttributeName,
[UIColor grayColor],NSForegroundColorAttributeName,
nil];
//Will gray color and resize the € symbol
[amountText setAttributes:dictionaryOfAttributes range:NSMakeRange(0, 1)];
myUILabel.attributedText = amountText;