如何创建具有清晰背景的按钮

Posted

技术标签:

【中文标题】如何创建具有清晰背景的按钮【英文标题】:How to create a button with a clear background 【发布时间】:2014-03-11 03:12:56 【问题描述】:

如何创建一个除了图像之外透明的 UIButton?

我有透明背景的 PNG。我用它创建了一个按钮,然后我得到了蓝色的图像。

如果我将 tintColor 设置为 clearColor,色调会消失,但黑色图像也会消失。

我一直使用 UIButtonTypeSystem 作为按钮类型。

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ; // Does nothing
button.tintColor = [UIColor clearColor] ;  // Makes the button go away.

【问题讨论】:

【参考方案1】:

为了有一个透明的按钮,你应该把它设为自定义类型。所以你的代码会变成:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ; // This is not necessary, unless you want to specify a color - say [UIColor redColor] - for the button

由于 UIButtonTypeCustom 的行为方式与 UIButtonTypeSystem 不同,因此您应该查看各种布尔标志来设置特定的特征。它们必须手动设置或通过 Interface Builder 设置。这是list 的属性。

【讨论】:

【参考方案2】:
UIButton *button = [UIButton UIButtonTypeCustom] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal];

你只需要使用UIButtonTypeCustom,不需要为UIButton设置任何backgroundColor或tintColor。

【讨论】:

【参考方案3】:

您需要使用UIButtonTypeCustom

【讨论】:

【参考方案4】:

只需更改一行使用 UIButtonTypeCustom 而不是 UIButtonTypeSystem

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ;

【讨论】:

以上是关于如何创建具有清晰背景的按钮的主要内容,如果未能解决你的问题,请参考以下文章