I have a UICustomButton(subclass of UIButton) in the interface builder. I want change this button's frame inside UICustomButton.
I tried following code:
// 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;
in awakeFromNib:, drawRect:
none of them worked, the result is unchanged.
Neither awakeFromNib
nor drawRect:
is appropriate.
You can change its frame in layoutSubviews
, but you might run into trouble if your app uses auto layout.
Don't do that! That's bad architecture!
A view should never change it's own frame. It's always the parent view resizing its children. If you detect you need another frame inside your view: send out a delegate call to the parent view and change the frame in there. the delegate method could look like this
- customButton:(UIButton *)button requestNewFrame:(CGRect)frame
{
button.frame = newFrame;
// some storing method so you remember the frame on rotations and stuff
}
Just as a reminder: child views are always resized in
- (void)layoutSubviews //UIView
- (void)viewDidLayoutSubviews //UIViewController
That makes your code safe for different UIInterfaceOrientations and different devices.
I'd put it in viewDidLoad. If you put it in a recurring method, it will increase in size each time it's called.
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.