Change UIView width in Swift 5

Viewed 425

I'm working on the Swift project now and stuck on how to change my UIView's width in code.

In my storyboard, I have gray-colored UIView.

Gray view on right side of landscape device

I set its width, in the inspector, as

equals: 160

However, I don't want to give an exact number for my UI, so I made @IBOutlet to it and tried to set the value as 0.2 * parent view's width. But when I build I cannot see the width changes...

@IBOutlet weak var parentView: UIView!
@IBOutlet weak var grayArea: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    grayArea.frame.size.width = parentView.frame.size.height * 0.2
}

I searched similar questions on Stack Overflow but none of them worked for my code. Could anyone please point me what I'm doing wrong in here?

1 Answers

As Sweeper said, you won't be able to change the frame of views that have constraints added. Instead, if you want the width to always equal 0.2 of the parent, you should just use a proportional constraint.

  1. Right-click on the gray view, and hold
  2. Drag to the parent view, then release
  3. Choose Equal Widths
  4. In the attributes inspector, select the constraint that you just added
  5. Click Edit
  6. Enter 0.2 for the "Multiplier"
  7. Done!

GIF of the above steps

Related