您可以通过以下方式使用图层或渐变图层:
- (void) viewDidLoad
{
[super viewDidLoad];
CAGradientLayer *gradient = [CAGradientLayer layer];
loginButton.clipsToBounds = YES;
UIColor *topColor = [UIColor colorWithRed:255/255 green:255/255 blue:255/255 alpha:0.9];
UIColor *middleColor = [UIColor colorWithRed:61.0/255 green:130.0/255 blue:244.0/255 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:24.0/255 green:77.0/255 blue:214.0/255 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)topColor.CGColor,
(id)middleColor.CGColor, (id)bottomColor.CGColor, nil];
gradient.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:0.05f],
[NSNumber numberWithFloat:0.7],
nil];
gradient.frame = [[loginButton layer] bounds];
gradient.cornerRadius = 4.0;
gradient.borderWidth = 0.5;
[loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[loginButton.layer insertSublayer:gradient atIndex:0];
[loginButton addTarget:self action:@selector(loginTouchDown:)
forControlEvents:UIControlEventTouchDown];
[loginButton addTarget:self action:@selector(loginTouchUp:)
forControlEvents:UIControlEventTouchUpOutside];
}
- (IBAction)loginTouchDown:(id)sender
{
CAGradientLayer *gradient = [loginButton.layer.sublayers objectAtIndex:0];
UIColor *topColor = [UIColor colorWithRed:24.0/255 green:77.0/255 blue:214.0/255 alpha:1.0];
UIColor *middleColor = [UIColor colorWithRed:24.0/255 green:77.0/255 blue:214.0/255 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:24.0/255 green:77.0/255 blue:214.0/255 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)topColor.CGColor, (id)middleColor.CGColor,
(id)bottomColor.CGColor, nil];
}
- (IBAction)loginTouchUp:(id)sender
{
CAGradientLayer *gradient = [loginButton.layer.sublayers objectAtIndex:0];
UIColor *topColor = [UIColor colorWithRed:255/255 green:255/255 blue:255/255 alpha:0.9];
UIColor *middleColor = [UIColor colorWithRed:61.0/255 green:130.0/255 blue:244.0/255 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:24.0/255 green:77.0/255 blue:214.0/255 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)topColor.CGColor,
(id)middleColor.CGColor, (id)bottomColor.CGColor, nil];
}
- (IBAction)loginButton:(id)sender
{
[self loginTouchUp:sender];
[self doLogin];
}
登录按钮在故事板中定义并分配给本地视图属性。
(在 *.h 文件中)
@interface LoginViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic, retain) IBOutlet UIButton *loginButton;
@end
(在 *.m 文件中)
@synthesize loginButton;
在 viewdidload 中,我们为正常状态和推送状态定义了梯度层。然后我们在 up/down 事件上操作它们。我们还需要 loginButton() 作为按钮处理程序来执行操作。这样,此按钮行为理想地与普通按钮相同。好像就是这个了
您可以在 iphone 应用商店中找到它的工作原理示例。有一个名为 Torchoo 的免费应用程序。当你运行它时,它首先显示的是登录屏幕。它有登录按钮。按下它看看这是不是你需要的。此代码来自该项目。