skip to Main Content

The Question


how can I keep Buttons, Images, Buttons…Views rounded in big screens when using constraints of ( buttons, images….views ) equal width and height to superview using swift


The Code I’ve Tried

I tried this block of code and It works fine in small screens like SE..until 8 :

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
roundedObject.layer.cornerRadius = roundedObject.frame.width / 2
roundedObject.clipsToBounds = true
}

the shape of the different sizes screens

my object constraints:
screen1 screen2 screen3

2

Answers


  1. Probably you’re doing that in viewDidLoad method where the frames didn’t get the final value yet (initially they get the values from the storyboard from where they were instantiated. So if in the storyboard preview the size is f.e. 300×300, in the viewDidLoad it also will be 300×300).
    So either do that in the viewDidLayoutSubviews or create a subclass and do that in the layoutSubviews.

    class RoundedButton: UIButton {
        override func layoutSubviews() {
            super.layoutSubviews()
            layer.corderRadius = bounds.width / 2
            layer.masksToBounds = true
        }
    
    }
    
    Login or Signup to reply.
  2. the issue is your constraint

    you will not get a square by using proportional width and proportional height constraint together like that, because different device will have different height and width

    my suggestion is to use only one proportional width or proportional height (which one you want) and use aspect ratio constraint 1:1 on the roundedObject

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search