@Christopher Fairbaim 建议使用 UIButtonTypeCustom 是正确的。使用 UIButtonTypeRoundedRect 会给你透明区域的白色背景。
然而,在 Interface Builder 中进行连接有其局限性。如果您想从数据集或基于用户输入动态生成 UIView、UIButton 和资产,则以编程方式执行此操作是可行的方法。
创建按钮:(注意:这也适用于其他 UIButtonTypes,但我在这个特定的透明度示例中使用了 UIButtonTypeCustom。)
UIButton *btnName = [UIButton buttonWithType:UIButtonTypeCustom];
要更改所需的属性:
btnName.backgroundColor = [UIColor clearColor];
btnName.frame = CGRectMake(100, 100, 72, 37); //(X coord, Y coord, width, height)
[btnName addTarget:myActionClassName action:@selector(myActionName) forControlEvents:UIControlEventTouchUpInside];
要为各种状态添加图像(假设这些是透明的 .png):
UIImage *btnNameImageNormal = [UIImage imageNamed:@"btnNameNormal.png"];
[btnName setBackgroundImage:btnMenuImageNormal forState:UIControlStateNormal];
UIImage *btnNameImagePressed = [UIImage imageNamed:@"btnNamePressed.png"];
[btnName setBackgroundImage:btnNameImagePressed forState:UIControlStateHighlighted];
要将按钮添加到视图(从 viewController 类中):
[self addSubview:btnName];
(请原谅任何拼写错误,因为我从我的一个项目中复制和粘贴并试图概括命名。)