I'm trying to set the font and text color for an attributed string like this:
var attributedString = NSMutableAttributedString(string: myText, attributes: [.font : myFont, .foregroundColor: myTextColor])
Later on, I'm adding more text to this attributed string.
If the myText variable contains some text this works great - the text is displayed with the correct font and text color. However, if myText is an empty string, the attributes aren't added, which means that when I later add more text to the attributed string, it's displayed in black with the default Helvetica 12px font.
Is it possible to add attributes to an attributed string even if the actual text is an empty string?
I'm using this in a UITextView and if the user removes all text in the textview, causing the attributed string to be an empty string, all text formatting is removed as well, which means that any further text additions will be displayed using the default Helvetica font, instead of the font I wish to use.
Related
I have search bar and table view. I can filter table view items based on search bar text. But I have to change found letter's color. For example if I write HE to search bar, I want to show HELLO in table view but the color of HE should different than LLO.
Thanks for ideas.
use NSMutableAttributedString for your concept, Here I tell the logic customize yourself where you need (must call in inside the cellForRow)
lblcheck.text = "hello" // is the original text
lblcheck.textColor = UIColor.red // initally set the whole color for your text
//Create mutable string from original one
let attString = NSMutableAttributedString(string: lblcheck.text!)
//Fing range of the string you want to change colour
//If you need to change colour in more that one place just repeat it
let range: NSRange = (lblcheck.text! as NSString).range(of: "he", options: .caseInsensitive) //he in here use searchBar.text
attString.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: range) // here set selection color what ever you typed
//Add it to the label - notice its not text property but it's attributeText
lblcheck.attributedText = attString
Text color change can be done by using NSAttributedString. When you show your search results, in your cellForRow delegate method, get search string and replace the word in your textView with NSAttributedString version. You can change color for the specific string in your NSAttributedString.
This is the general idea without seeing any code.
I have a convenience extension like this:
extension NSMutableAttributedString {
func append(string: String, attributes: [String: Any]) {
let attributed = NSMutableAttributedString(string: string)
let range = NSRange(location: 0, length: string.utf16.count)
for (attribute, value) in attributes {
attributed.addAttribute(attribute, value: value, range: range)
}
append(attributed)
}
}
I'm styling text in my UILabel thusly:
let normalAttributes = [NSForegroundColorAttributeName: darkGray]
let lightAttributes = [NSForegroundColorAttributeName: lightGray]
let text = NSMutableAttributableString()
text.append("Part 1", attributes: normalAttributes)
text.append("Part 2", attributes: lightAttributes)
All of this within a custom UITableViewCell class. What's happening is that the text is rendering with the base color in the NIB file, rather than the custom foreground color as per my attributed string - until I do something (like scroll around) that causes cell reuse, after which suddenly the colors render correctly.
I can't seem to find anything wrong with the lifecycle of the object, and there's no other place that's messing with this label. The label, fwiw, is an IBOutlet, so I'm not creating a new one each time or anything strange.
Turns out it's the same problem as:
Attributed string in tableviewcell not showing bold text until the cell is dequeued and reloaded
So it's solved by setting the font & color to nil on the label before setting the attributeText. Annoying, but easy enough to do that work-around.
As #Kiril Savino suggested. Setting up Font & Color of UILabel to nil is do easy work-around to get it done.
But one more thing I noticed today is Default Font used from Storyboard or XIB.
It should be System Font from Storyboard or XIB to make this work.
If you have used other Custom Font, then it won't work.
So, make sure Default Font of UILabel should System Font.
Thank you.
How do I add padding to a substring of UITextView that is a NSMutableAttributedString (shown here highlighted in yellow)?
I currently have the attributed text (image 2) without any padding around the attributed text, but need to add some padding to it (image 3), which is some spacing around the highlighted text only (not the entire UITextView.
Here is a close-up comparing how the NSMutableAttributedString with/without padding (this padding should not apply to the rest of the text which unattributed):
Here's how I'm currently getting the text from the UITextView (after finding the range of text I want to highlight and storing the attributed text in attributedText):
var highlightedText = NSMutableAttributedString(string: "this text is highlighted")
let highlightedRange = NSRange(location: 0, length: highlightedText.characters.count)
highlightedText.addAttribute(NSBackgroundColorAttributeName,
value: UIColor.yellow, range: highlightedRange)
attributedText.replaceCharacters(in: highlightedRange, with: highlightedText)
I'm trying to apply two attributes to a string, one for kerning (NSKernAttributeName) and one for the font (NSFontAttributeName). Although I've checked and rechecked 1000 times, I can only get the kerning attribute to be applied to the string. Here's my setup:
let runAtTitle = "RUN AT"
var attRunAt = NSMutableAttributedString(string: runAtTitle)
let font = UIFont(name: "HelveticaNeue-Bold", size: 76.0)!
let attrs = [NSFontAttributeName: font, NSKernAttributeName: -3.0]
attRunAt.addAttributes(attrs, range: NSMakeRange(0, attRunAt.length))
runAtLabel.attributedText = attRunAt
When I build the app, the kerning is applied to my string, but the font is not. It uses the default 12pt Helvetica. Please tell me I'm doing something wrong.
I just tried your code in Playground and it works fine. Most likely you are setting the text attribute of the label after setting the attributedText. That will revert the string to the normal label string with its attributes, or perhaps for some strange reason keep the kern attribute.
Here is what I get with your code:
and after adding
label.text = "RUN AT"
I have a label where there is text which should be bold and with another font size. Is there any possibility to do it like the line break ("Hello \n World!") with a command or do I have to make another label for this?
Thanks!
Look at the API for NSAttributedString -- it allows you to create a string that specifies portions of the string that should be styled with specific text styles and/or fonts. The resulting object can be used instead of a plain string with UILabel (and other UI elements) by setting the label's attributedText property instead of the usual text property.
To make just the word "bold" appear in 18 point bold, try something like the following:
var label = UILabel()
let bigBoldFont = UIFont.boldSystemFontOfSize(18.0)
var attrString = NSMutableAttributedString(string: "This text is bold.")
attrString.addAttribute(kCTFontAttributeName, value: bigBoldFont, range: NSMakeRange(13, 4))
label.attributedText = attrString
The range specified determines the portion of the string to which the named attributed (in this case, the font) should be applied. And note that the parameters to NSMakeRange are the starting character position and the length of the range.