[英]How to change the frame of a UIView subclass on device orientation which is programmatically created?
[英]How to programmatically change UIView's frame inside an UIView Subclass?
我在界面生成器中有一个UICustomButton(UIButton的子类)。 我想在UICustomButton中更改此按钮的框架。
我尝试了以下代码:
// make it 10 points wider and higher
CGRect newFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width + 10, self.frame.size.height + 10);
self.frame = newFrame;
在awakeFromNib:, drawRect:
它们都不起作用,结果保持不变。
awakeFromNib
和drawRect:
都不适合。
您可以在layoutSubviews
更改其框架,但是如果您的应用程序使用自动布局,则可能会遇到麻烦。
不要那样做! 那是糟糕的架构!
视图永远不应更改其自身的框架。 始终将其子视图调整为父视图。 如果检测到视图中需要另一个框架,请执行以下操作:向父视图发送委托调用,然后在其中更改框架。 委托方法可能看起来像这样
- customButton:(UIButton *)button requestNewFrame:(CGRect)frame
{
button.frame = newFrame;
// some storing method so you remember the frame on rotations and stuff
}
提醒一下:子视图总是在
- (void)layoutSubviews //UIView
- (void)viewDidLayoutSubviews //UIViewController
这使您的代码对于不同的UIInterfaceOrientations和不同的设备而言都是安全的。
我将其放在viewDidLoad中。 如果将其放在重复使用的方法中,则每次调用它的大小都会增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.