ios - 以编程方式设置按钮背景图像 iPhone

标签 ios iphone xcode image button

在 Xcode 中,如何将 UIButton 的背景设置为图像?或者,如何在 UIButton 中设置背景渐变?

最佳答案

完整代码:

+ (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];

    UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    // in case the parent view draws with a custom color or gradient, use a transparent color
    button.backgroundColor = [UIColor clearColor];

    return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

设置图像:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

删除图像:

[button setBackgroundImage:nil forState:UIControlStateNormal];

关于ios - 以编程方式设置按钮背景图像 iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723831/

相关文章:

iOS 11 在使用大标题时无法正常滚动到顶部

ios - 添加 UIImage 会忽略 UIImageView 框架并调整其大小

javascript - 如何检测 Cordova WebView 何时完全完成加载?

ios - 将希伯来语消息分配给 NSString 有时会显示 html 标记,如 quot&

swift - 如何将 Swift 连接到托管在 Google Cloud 上的 postgresql 数据库

xcode - 为什么 Xcode 10 会崩溃?

iOS map 标记和当前位置未显示

iphone - 仅显示/使用 MFMailComposeViewController 中的 "To: "字段

iphone - iOS平移和缩放动画

ios - 在 swift3 中安装 pod 后,链接器命令失败,退出代码为 1(使用 -v 查看调用)