ios 以编程方式更改 UIView 大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18580975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:56:58  来源:igfitidea点击:

Changing UIView size programmatically

iphoneiosuiview

提问by onivi

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

我有一个 UIView,我想在用户触摸按钮时更改大小。

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.

它们都不起作用,不要改变任何东西。我想为 UIView 设置固定的宽度和高度。

回答by Tim Bodeit

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.

如果我理解正确,您想更改self.myview. 但是,您绝不会设置它的框架。相反,您正在尝试调用sendFrame:视图控制器和一些搜索字段。我很惊讶,前一个没有给你一个编译器错误。

Objective C

目标 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

回答by Filoux

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

就我而言,我对视图的宽度有限制,因此我无法像 Tim 所说的那样更改宽度。

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

我所做的:我在我的 constaint 上创建了一个出口,myviewWidthConstraint例如调用。然后我使用这个插座来改变我的视图宽度,如下所示:

mycell.myviewWidthConstraint.constant = newSize;

回答by J-Dizzle

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);

回答by lbsweek

view.frame  = newframe;

or

或者

view.center = newcenter;