Filip
Filip

Reputation: 1864

iOS: Custom button (subclass of UIButton) - cannot change border properties

I want to have custom button consisting of green background, white text and no border. I created class ThemedButton which inherist from UIButton. I then change button properties in awakeFromNib method.

For some reason changing background and title colors work fine, but manipulating border properties (or even rounded corners) does not. My button has green background with white text but also ugly blue border.

My implementation is below.

EDIT: Sorry for my confusing properties. I also tried to set border color to the same as background to get rid of it this way.

import UIKit

class ThemedButton: UIButton {

    override func awakeFromNib() {
        super.awakeFromNib()

        // Works
        setTitleColor(UIColor.white, for: .normal)
        layer.backgroundColor = GREEN_COLOR.cgColor

        // Does not work
        layer.borderWidth = 0
        layer.borderColor = GREEN_COLOR.cgColor
        layer.cornerRadius = 5

    }

}

Upvotes: 1

Views: 985

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

set the width of the border

 layer.borderWidth = 5

This works

class ThemedButto22n: UIButton {

   override func awakeFromNib() {
      super.awakeFromNib()


  }

 override func layoutSubviews() {
    super.layoutSubviews()
    // Works
    setTitleColor(UIColor.white, for: .normal)
    layer.backgroundColor = UIColor.green.cgColor

    // Does not work
    layer.borderWidth = 5
    layer.borderColor = UIColor.red.cgColor
    layer.cornerRadius = 5


}

}

Upvotes: 3

Related Questions