Changing size of UIButton while using Autolayout?

2019-06-09 16:20发布

问题:

I'm pretty new to ios. I'm working on a project which is going to frequently use a certain UIView class throughout the application. This class is simply an image that does some transparency stuff with the background color. This works fine so far. This class sometimes exists as a lone UIView, and sometimes as a button subview.

When I add this UIView to a UIButton as a subview, the full contents of the UIView are displayed at full size, but the clickable area of the button remains the size defined in the xib unless Use Autolayout is turned off (even if I manually try to set the button's frame.)

I would like to put a UIButton on the xib as a placeholder, and then later define its size/clickable area based on the size of the overlay image which the UIView that was initialized with.

Should this be possible, or am I misinterpreting the usage of xib files/autolayout?

under ViewDidLoad I have...

- (void)viewDidLoad{

    [theButton addSubview:_theView];
    CGRect buttonFrame = theButton.frame;
    buttonFrame.size = CGSizeMake(_theView.getSize.width,_theView.getSize.height);
    [theButton setFrame:buttonFrame];
}

However, the frame stays the same size when I print the button info before and after I try calling setFrame.

(note that '_theView.getSize' was added by me)

回答1:

  1. Under Autolayout, views don't have frames at viewDidLoad. Try your code in viewWillAppear: or viewDidLayoutSubviews.
  2. Under Autolayout, you don't set frames. You edit constraints instead. Setting a frame will work until the next layout pass, when your layout will revert to that described by your constraints.
  3. To size a button to fit a subview, you can try something like this (in visual format language): |-[theView]-| but it would depend what constraints are in place from your xib.