Adding underline attribute to partial text UILabel in storyboard - ios

How can I underline partial text of UILabel using only storyboard? I am able to do this in code and I'm able to underline the entire text of a label, but not just one or two words in the string.

select the UILabel and go to Attribute Inspector section.
Change the text value from plain to Attributed .
Select the particular part of text which you want to Underline .
Note: If u want full text to be Underline select full text.
Now right click and change the font to Underline.
It will Underline the text

Steps:-
Go to TextEdit and create your UILabel text with underline.
Change UILabel text to Attributed (Attributed Selector).
Copy Underlined text and assign to UILabel.

Through code:
func underLineText(text: String)-> NSMutableAttributedString
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSMutableAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedText.length))
return attributedText
}
//calling of func
yourLbl.attributedText = underLineText(text:yourLbl.text!)
List of other underline Types
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.single.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.thick.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.double.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDash.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDashDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.patternDashDotDot.rawValue
NSMutableAttributedString.Key.underlineStyle = NSUnderlineStyle.byWord.rawValue

Related

Programatically change some words' color in an UITextView

So I have an UITextView with some text and I want everytime the user inputs, for example, the word "while", after it has been written it should change into purple. Also, I have another UITextView just to display content, no user interaction enabled, and I want that everytime the view appears, all the "while" words to also be purple. How do I do this? Can you help me, please? Thank you!
Here's what I've tried so far:
let initialText = textView.text!
let string_to_color = "while"
let range = (initialText as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: initialText)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.purple, range: range)
textView.attributedText = attribute
But it colors only the first word. This is for the user interaction disabled text field. I haven't figured out how to do it for the text field that contains the words that the user inputs.
You are not getting the range correctly, here is an example of using attributed strings in Swift 3.0:
// get initial text as a String type (you will get this from your textview)
let initialText = "Swift Attributed String"
// create an attribute for the text color, I chose blue color
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
// create the attributed string and add the blue color attribute
let myString = NSMutableAttributedString(string: initialText, attributes: myAttribute )
// range starting at location 6 with a lenth of 10: "Attributed"
var myRange = NSRange(location: 6, length: 10)
// OR get range of specific string in initialText
let newRange = (initialText as NSString).range(of: "Attributed")
// change the range of the word "Attributed" to have red text color
myString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: newRange)
// create another attribute for highlighting
let anotherAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]
// set the range of the "Attributed" part of the string to a yellow highlight
myString.addAttributes(anotherAttribute, range: newRange)
You can use this strategy to do whatever formatting you need to do with your string. Just make sure that the range that you are getting is correct.

Adding padding to NSMutableAttributedString in UITextView

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)

String with multilpe attributes in swift

I am working on an app on which i had to make the text in a UITextView bold or italic or underlined. So i came up with this solution to make the selected range from the textView bold. The same way i can make it italic and but not underlined, don't know how.
//MARK: Bold Bar Button
func boldBarButtonClicked(sender : UIBarButtonItem)
{
if let selectedTextRange = self.textView.selectedTextRange
{
let beginningOfDocument = self.textView.beginningOfDocument
let startingPoint = self.textView.offsetFromPosition(beginningOfDocument, toPosition: selectedTextRange.start)
let selectedTextLength = self.textView.offsetFromPosition(selectedTextRange.start, toPosition: selectedTextRange.end)
let dict : Dictionary<String, AnyObject> = self.textView.textStorage.attributesAtIndex(startingPoint, effectiveRange: nil)
if let currentFont = dict[NSFontAttributeName] as? UIFont
{
let fontDescriptor = currentFont.fontDescriptor()
let changedFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
let updatedFont = UIFont(descriptor: changedFontDescriptor, size: 0.0)
let updatedDict = [NSFontAttributeName : updatedFont ]
self.textView.textStorage.beginEditing()
let selectedNSRange = NSMakeRange(startingPoint, selectedTextLength)
self.textView.textStorage.setAttributes(updatedDict, range: selectedNSRange)
self.textView.textStorage.endEditing()
// Put bold tag inside letters
}
}
}
So basically when the user sees the textView i have to make the text bold. So i thought of putting the text in between bold tag just the same as html. So that i can loop through the characters and see whether there is any text which is bold or italic or underline.
Am i doing it the correct way? Finding the selected range make it bold or italic or underlined and then put the tag inside the reference string, finally passing this string to the server with tags involved, so that others can see where comes the bold or italic or underlined characters.
How this will work if the same string has multiple attributes like, if the string "alvin" has bold and italic and underline, it will be like U I B "alvin' /U /I /B (tags are same as html bold, italic, underline) correct? How can i do find these in Swift, i thought about it a lot and tired of using regular expressions and looping through the string. But could not get the proper result. Thanks in advance.

Swift - Changing font size inside label

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.

Adding underline to UILabel attributed string from the storyboard fails

From the storyboard I select the UILabel in question
Then in Attribute Inspector > Label > [I choose] Attributed
Also in Attribute Inspector > Label > Text> [I select the content]
Then I click on the font icon and choose underline
Basically, any change that I select from the Fonts window that pops up does not take effect.
Has anyone ever successfully add underline from the storyboard?
Note: I already know how to do this in code. I want to avoid adding code.
Here is the solution in storyboard:
Open the Attribute Inspector (make sure label is selected), Change the dropdown value from 'Plain' to 'Attributed'. Now a a small text editor will be visible under the font of the label. Select the text of the label, right click and change the font to 'underline'.
I also have attached a screenshot and successfully underlined a text using storyboard in XCode 7.0.1
Underline your text in TextEdit(cmd-U) and copy-paste it in Attribute Inspector > Label > Text > Attributed.
Select label -> Attribute editor -> Title = Attributed
Select the text of the label in the text view in the editor -> Right click -> Font -> check Underline
If the change is not visible -> resize the label
You can make text underline from storyboard like this.
But when you change the text programatically it will override and underline will gone.
So if you have to change the text on runtime. Do this.
For Swift 3
let text = myLabel.text
let textRange = NSMakeRange(0, (text?.characters.count)!)
let attributedText = NSMutableAttributedString(string: text!)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
myLabel.attributedText = attributedText
For Swift 4
let text = myLabel.text
let textRange = NSRange(location: 0, length: (text?.count)!)
let attributedText = NSMutableAttributedString(string: text!)
attributedText.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
myLabel.attributedText = attributedText
Leave it set to plain. Make all of your changes. Then change it to attributed.
The Designer Way - Highly Customisable Version
I personally prefer to customise my design(s) as much as possible. Sometimes, you will find that using the built-in underline tool is not easily customisable.
To do something like the following, I have posted an example in How to make an underlined text in UILabel?

Resources