Search code examples
iosswiftconstraints

Rounded UIButton - iPad size


I have custom UIButton to have rounded edges

import UIKit

class RoundedButton: UIButton {

    override init(frame: CGRect) {

        super.init(frame: frame)

        self.layer.cornerRadius = self.bounds.width * 0.5
        self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
        self.setTitleColor(UIColor.white, for: UIControlState.normal)
    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        self.layer.cornerRadius = self.bounds.width * 0.5
        self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
        self.setTitleColor(UIColor.white, for: UIControlState.normal)
    }

}

Now I am using this "RoundedButton" (size of 110, 110) in a UIViewcontroller's XIB file and the constraints are set to maintain the aspect ratio w.r.t UIViewcontrollers view.

The button looks rounded in iPhone simulators but the button is NOT rounded in iPad simulator. When I set the layer.cornerRadius property in viewDidAppear then the button is rounded in iPad simulator.

Please see images

enter image description here

enter image description here

I am looking for an alternative solution than re-defining layer corner radius again in viewDidappear.

Thanks


Solution

  • Override layoutSubviews function:

    import UIKit
    
    class RoundedButton: UIButton {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
            self.setTitleColor(UIColor.white, for: UIControlState.normal)
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
            self.setTitleColor(UIColor.white, for: UIControlState.normal)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            self.layer.cornerRadius = self.bounds.width * 0.5
        }
    }