UIButton 的大小与封闭的 UIImageView 对象不同

Posted

技术标签:

【中文标题】UIButton 的大小与封闭的 UIImageView 对象不同【英文标题】:UIButton's size is different to the enclosed UIImageView object 【发布时间】:2015-08-30 05:02:56 【问题描述】:

我放了一些查看UIButton 对象并使用setImage:forState: 方法将图像设置为按钮。 图像尺寸为 19x8。 并且,调用[button setTranslatesAutoresizingMaskIntoConstraints:NO] 方法来调整自动布局。自动布局只是设置按钮的位置。 然后,我发现按钮大小是 19x22,封闭的图像大小是 19x8。图像位置垂直居中。

为什么按钮和图片不一样? 我怎样才能使它们变成相同的大小?


我添加了示例代码。

UIButton *button = [[UIButton alloc] initWithFame:CGRectZero];
[button setImage:[UIImage imageNamed:@"buttonImage"] forState:UIControlStateNormal]];
[button setTranslatesAutoresizingMaskIntoConstraints:NO];

就是这样。

【问题讨论】:

如果您列出了按钮的约束条件以及它们的实际代码,将会很有帮助。 【参考方案1】:

如果你想让按钮和图片一样大小,那么先获取图片的大小。

CGFloat width = myImage.size.width;
CGFloat height = myImage.size.height;

CGRect myRect = CGSizeMake:(myButton.frame.size.x,myButton.frame.size.y,width,height); //x and y with respect with superview.
[myButton setImage:myImage forState:UIControlStateNormal];
myButton.frame = myRect;

【讨论】:

嗯...不幸的是,我不使用设置框架,因为使用自动布局。 使用自动布局,按钮的矩形会根据设备而变化? 检查编辑,此代码将按钮大小更改为图像大小,而不更改其位置

以上是关于UIButton 的大小与封闭的 UIImageView 对象不同的主要内容,如果未能解决你的问题,请参考以下文章

uibutton与图像

设置 UIButton 的 backgroundImage 时不调整大小,但定位

如何允许自动调整UIButton的大小以满足间距约束

如何在 QuickDialog 中将 UIImageView 添加到 Qsection?

UIButton 上的 UIImage 模糊

使字体大小适合封闭按钮?