简体   繁体   English

使用自动布局时更改UIButton的大小?

[英]Changing size of UIButton while using Autolayout?

I'm pretty new to ios. 我是ios的新手。 I'm working on a project which is going to frequently use a certain UIView class throughout the application. 我正在一个项目中,该项目将在整个应用程序中频繁使用某个UIView类。 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. 此类有时作为一个单独的UIView存在,有时作为一个按钮子视图存在。

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.) 当我将此UIView作为子视图添加到UIButton时,UIView的全部内容以完整大小显示,但是按钮的可单击区域保持在xib中定义的大小,除非关闭了“使用自动布局”(即使我手动尝试设置按钮的框架。)

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. 我想将UIButton放置在xib上作为占位符,然后稍后根据初始化时使用的UIView的覆盖图像的大小来定义其大小/可单击区域。

Should this be possible, or am I misinterpreting the usage of xib files/autolayout? 这是否可能,或者我是否误解了xib文件/自动布局的用法?

under ViewDidLoad I have... 在ViewDidLoad下,我有...

- (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. 但是,当我尝试调用setFrame之前和之后打印按钮信息时,框架保持相同的大小。

(note that '_theView.getSize' was added by me) (请注意,“ _ theView.getSize”是我添加的)

  1. Under Autolayout, views don't have frames at viewDidLoad . 在“自动布局”下,视图在viewDidLoad处没有框架。 Try your code in viewWillAppear: or viewDidLayoutSubviews . viewWillAppear: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]-| 要调整按钮大小以适合子视图,可以尝试以下操作(以视觉格式的语言): |-[theView]-| but it would depend what constraints are in place from your xib. 但这取决于您的xib有哪些约束条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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