swift实现button背景色和下划线功能

版权声明:本文为博主原创文章,未经博主允许不得转载。深圳夸克时代在线技术有限公司 官网:http://www.kksdapp.com https://blog.csdn.net/wahaha13168/article/details/82903866
extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControlState) {

        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))

        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)

        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))

        let colorImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, for: forState)

    }

    func underline() {

        guard let text = self.titleLabel?.text else { return }

        let attributedString = NSMutableAttributedString(string: text)

        attributedString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: text.count))

        self.setAttributedTitle(attributedString, for: .normal)

    }

}

猜你喜欢

转载自blog.csdn.net/wahaha13168/article/details/82903866