Change UIButton border color on highlight

后端 未结 6 798
礼貌的吻别
礼貌的吻别 2021-02-03 23:53

I\'ve got a simple custom UIButton, to which I added:

button.layer.bordercolor = [[UIColor blueColor]CGColor];

However, I want to change the .b

6条回答
  •  灰色年华
    2021-02-04 00:45

    For a solution that doesn't involve subclassing, you could always add an extension method to UIButton. E.g.

    func setBackgroundColor(_ backgroundColor: UIColor,
                            borderColor: UIColor,
                            borderWidth: CGFloat,
                            cornerRadius: CGFloat,
                            forState state: UIControlState) {
    
        UIGraphicsBeginImageContext(bounds.size)
        guard let context = UIGraphicsGetCurrentContext() else { return }
    
        if borderWidth > 0 {
            layer.borderWidth = 0 // hide the layer's border if we're going to draw a border
        }
    
        context.addPath(UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth, dy: borderWidth), cornerRadius: cornerRadius).cgPath)
        context.setStrokeColor(borderColor.cgColor)
        context.setFillColor(backgroundColor.cgColor)
        context.setLineWidth(borderWidth)
    
        context.closePath()
        context.strokePath()
        context.fillPath()
    
        let buttonImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(buttonImage, for: state)
    }
    

提交回复
热议问题