简体   繁体   中英

Changing UIView size programmatically

I've a UIView, I want to change the size when user touches a button.

CGRect newFrame = self.myview.frame;

newFrame.size.width = 200;
newFrame.size.height = 200;
[self setFrame:newFrame];

CGRect newFrame = self.searchField.frame;

newFrame.size.width = 200;
newFrame.size.height = 200;
self.searchField.frame=newFrame;

None of them works, don't change anything. I want to set fixed width and height to UIView.

If I understand correctly, you want to change the size of self.myview . However at no point you are setting the frame of it. Instead you are trying to call sendFrame: on the view controller and some search field. I'm surprised, that the former one didn't give you a compiler error.

Objective C

CGRect newFrame = self.myview.frame;

newFrame.size.width = 200;
newFrame.size.height = 200;
[self.myview setFrame:newFrame];

Swift

var newFrame = myview.frame

newFrame.size.width = 200
newFrame.size.height = 200
myview.frame = newFrame

In my case, I had a constraint on the width of my view, so I couldn't change the width like Tim said.

What I've done : I created an outlet on my constraint, called myviewWidthConstraint for example. Then I used this outlet to change the width of my view like this :

mycell.myviewWidthConstraint.constant = newSize;

Size fields are read-only, just make a new one -

//Set height
let f = view.frame;      //Grab current
view.frame = CGRect(x: f.origin.x, y: f.origin.y, width: f.width, height: 200);
view.frame  = newframe;

要么

view.center = newcenter;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM