Underlining text in UIButton

后端 未结 18 1900
终归单人心
终归单人心 2020-11-29 15:56

Can anyone suggest how to underline the title of a UIButton ? I have a UIButton of Custom type, and I want the Title to be underlined, but the Interface Builder does not pr

18条回答
  •  猫巷女王i
    2020-11-29 16:09

    You can use this code to add underline with spacing in button.

    • When I tried to draw an underline from interface builder. It look like below image.

    1 - Interface builder reference

    • And after using below code I achieved the result as I wanted.

    2 - using described code

    public func setTextUnderline()
        {
            let dummyButton: UIButton = UIButton.init()
            dummyButton.setTitle(self.titleLabel?.text, for: .normal)
            dummyButton.titleLabel?.font = self.titleLabel?.font
            dummyButton.sizeToFit()
    
            let dummyHeight = dummyButton.frame.size.height + 3
    
            let bottomLine = CALayer()
            bottomLine.frame = CGRect.init(x: (self.frame.size.width - dummyButton.frame.size.width)/2, y: -(self.frame.size.height - dummyHeight), width: dummyButton.frame.size.width, height: 1.0)
            bottomLine.backgroundColor = self.titleLabel?.textColor.cgColor
            self.layer.addSublayer(bottomLine)
        }
    

提交回复
热议问题