Error404 Error404 - 1 year ago 68
Swift Question

Is it possible to add two labels inside an UIButton on Swift?

I have an

on my
project and I would like to use a font-awesome icon combined with a text inside of it.

I know that I can set a title to the button but, as far I need that the icon and the text will be in a different text-size, I cannot combine them in the same title tag. I also have thought about to use an image (to set the font-awesome icon) with an attributed title but then I cannot change the color of the font-awesome icon.

I know that I can get this behaviour adding two labels inside an
but I would like to know if it is possible to get this on an

Thanks in advance!

Answer Source

You can set attributed title of your button with attribute string something like,

 let attributedTitle = NSAttributedString(string: "Click Here",
attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
button.setAttributedTitle(attributedTitle, forState: .Normal)

You can set multiple color,font,size for particular texts or part of string.

another example,

 attributedTitle = NSMutableAttributedString(string: @"Click Here", attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])

   attributedTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

  button.setAttributedTitle(attributedTitle, forState: .Normal)

So, you can specify location by using NSRange and can set different color and font attributes for specified range!