Skip to content

Instantly share code, notes, and snippets.

@Erkened
Last active November 12, 2015 10:29
Show Gist options
  • Save Erkened/582569a7a50cdf3f931f to your computer and use it in GitHub Desktop.
Save Erkened/582569a7a50cdf3f931f to your computer and use it in GitHub Desktop.
//
// UIButton_Underlined.swift
// Audio Y
//
// Created by Jonathan Neumann on 31/10/2015.
// Copyright © 2015 Audio Y Ltd. All rights reserved.
//
import UIKit
class UIButton_Underlined: UIButton {
// Override the setTitle function in order to add an underline to the label
override func setTitle(title: String?, forState state: UIControlState) {
// If there is no title, just call super and return
guard let unwrappedTitle = title else{
super.setTitle(title, forState: state)
return
}
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: unwrappedTitle, attributes: underlineAttribute)
self.setAttributedTitle(underlineAttributedString, forState: state)
}
// Override the setTitleColor function in order to change the colour of the underline
override func setTitleColor(color: UIColor?, forState state: UIControlState) {
// If there is no color or no attributed title, just call super and return
guard let unwrappedColour = color, underlinedAttributedString = self.titleLabel?.attributedText as? NSMutableAttributedString else{
super.setTitleColor(color, forState: state)
return
}
underlinedAttributedString.addAttribute(NSForegroundColorAttributeName, value: unwrappedColour, range: NSRange(location: 0, length: underlinedAttributedString.length))
self.setAttributedTitle(underlinedAttributedString, forState: state)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment