Set and remove underline to UIButton iOS swift

 Solution:

extension UIButton {

    func underline(text: String) {

        let attributedString = NSMutableAttributedString(string: text)

        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))

        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))

        attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: text.count))

        self.setAttributedTitle(attributedString, for: .normal)

    }

    

    // MARK: - Remove underLine

    func removeUnderline(text: String) {

        let attributedString = NSMutableAttributedString(string: text)

        attributedString.addAttribute(NSAttributedString.Key.underlineColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))

        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: self.titleColor(for: .normal)!, range: NSRange(location: 0, length: text.count))

        self.setAttributedTitle(attributedString, for: .normal)

    }

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift