jay123456
jay123456

Reputation: 141

Resizing UIView in runtime

I have a UIView that's centered vertically and horizontally in my storyboard and has a fixed height (100) and width (300). Now I want that uiview to be resized (100, 100) during runtime.

I have tried this so far but nothing worked.

let cgRect = CGRect(x: 0, y: 0, width: 100, height: 100)

sampleView.draw(cgRect)

and

sampleView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)

and

sampleView.frame.size.height = 100
sampleView.frame.size.width = 100

Upvotes: 2

Views: 234

Answers (3)

ZeroOnet
ZeroOnet

Reputation: 15

You can do this:

override func layoutSubviews() {
    super.layoutSubviews()
    // set hight and width by constraints.
}

or:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // set hight and width by constraints.
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

Hook the width and height constraints as IBOutlet and in

@IBAction func btnClicked(_ sender: Any) {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    self.view.layoutIfNeeded()
}

Upvotes: 2

Niall Kiddle
Niall Kiddle

Reputation: 1487

To change the constraints during runtime via a button press you need to add it in an IBAction. In order to animate the change rather than it just jump, put the code in the UIView animation method:

@IBAction func buttonPressed() {

    self.widthCon.constant = 100

    self.heightCon.constant = 100

    UIView.animate(withDuration: 0.3, animations: {
        self.view.layoutIfNeeded()
    })
}

Upvotes: 0

Related Questions