Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline NSAttributed String as UIButton Title

My question is similar in theory to this one: iOS NSAttributedString on UIButton

I am looking to make the title of my button read as:

"An underlined string

Some text"

This needs to be done in swift and 100% programmatically.

I am attempting to do this by creating the underlined section using an NSMutableAttributedString and then appending that to the other text (which leads with a newline character). However, that gives me the error "Cannot assign value of type 'Void' ('aka'()') to type 'NSMutableAttributedString"

Code below:

var patientName = NSMutableAttributedString(string:"Patient Name", attributes: underlineAttributes)
var clickforinfomessage = NSMutableAttributedString(string: "\nclick for patient info")
clickforinfomessage = clickforinfomessage.appendAttributedString(patientName)
startVisitButton.setAttributedTitle(clickforinfomessage, forState: .Normal)
like image 946
DMop Avatar asked May 10 '16 06:05

DMop


People also ask

How do you make a UIButton multiline?

To make a multi-line text in UIButton, you insert a new line character ( \n ) wherever you want in button title and set lineBreakMode to byWordWrapping . You can adjust text alignment with . textAlignment .

What is attributed string?

Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources.


1 Answers

You can do it this way:

let dict1 = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]

let attString = NSMutableAttributedString()
attString.appendAttributedString(NSAttributedString(string: "Patient Name\n", attributes: dict1))
attString.appendAttributedString(NSAttributedString(string: "click for patient info", attributes: nil))
startVisitButton.setAttributedTitle(attString, forState: .Normal)
startVisitButton.titleLabel?.numberOfLines = 0
startVisitButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping

And result will be:

enter image description here

like image 117
Dharmesh Kheni Avatar answered Nov 14 '22 08:11

Dharmesh Kheni