如何使用渐变和突出显示创建UIButton?

时间:2013-02-04 16:48:37

标签: ios objective-c uibutton cagradientlayer

我正在尝试创建一个渐变背景的UIButton。我选择的工作正常,但按钮没有突出显示(默认行为是按钮变暗)。

这是我的按钮:

-(UIButton *)createLoginButtonForSize:(CGSize)size {
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.translatesAutoresizingMaskIntoConstraints = FALSE;
    loginButton.layer.cornerRadius = 8;
    loginButton.titleLabel.text = @"Login";

    [loginButton addTarget:self action:@selector(loginCheck:) forControlEvents:UIControlEventTouchUpInside];


    [loginButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[loginButton(WIDTH)]"
                                                                        options:0
                                                                        metrics:@{@"WIDTH": [NSNumber numberWithFloat:size.width]}
                                                                          views:NSDictionaryOfVariableBindings(loginButton)]];

    [loginButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[loginButton(HEIGHT)]"
                                                                        options:0
                                                                        metrics:@{@"HEIGHT": [NSNumber numberWithFloat:size.height]}
                                                                          views:NSDictionaryOfVariableBindings(loginButton)]];

    CAGradientLayer *layer = [UIColor greenGradient];
    layer.frame = CGRectMake(0, 0, size.width, size.height);
    layer.cornerRadius = 8;

    [loginButton.layer insertSublayer:layer atIndex:0];

    return loginButton;
}

我是否需要自己处理突出显示?

1 个答案:

答案 0 :(得分:5)

是的,您需要自己处理突出显示。您应该查看Jeff Lamarche非常容易使用的iPhone Gradient Buttons Project,而不是自己编写代码。它完全符合您的要求。它只是2个文件,因此很容易合并到您的项目中:

http://code.google.com/p/iphonegradientbuttons/source/browse/trunk/Classes/GradientButton.h http://code.google.com/p/iphonegradientbuttons/source/browse/trunk/Classes/GradientButton.m

以下摘自Jeff's Blog discussing the project

Imageless gradient buttons