以编程方式为UIButton创建高亮状态背景图像



我用以下代码创建了一个UIBarButton:

UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];    
[rightButton setFrame:CGRectMake(0, 0, 81, 30)];
[rightButton setBackgroundColor:[UIColor clearColor]];     
rightButton.layer.borderColor = [UIColor blackColor].CGColor;
rightButton.layer.borderWidth = 0.5f;
rightButton.layer.cornerRadius = 5.0f;
rightButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
[rightButton setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
[rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//set text according to sign in status
if (signIn) {
    [rightButton setTitle:@"5 votes left" forState:UIControlStateNormal]; 
} else {
    [rightButton setTitle:@"Sign in" forState:UIControlStateNormal];   
}
UIBarButtonItem * rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
self.navigationItem.rightBarButtonItem = rightBarButton;

获得的按钮具有所需的方面,但现在我需要的是,当按钮的状态被高亮显示时,应该有一个渐变效果褪色为黑色,让用户知道他已经按下了按钮,因为现在当我按下按钮时,视图没有发生任何变化,所以用户无法知道他已经按下了按钮。

我想探索一个不涉及设置所需状态的背景图像的选择,因为按钮的文本可以根据应用程序的配置动态地改变,所以我需要完全通过代码来做到这一点。

虽然这不会直接回答你的问题,但它可能会有所帮助。我必须动态地为按钮创建一些图形,并想出了一个使用core graphics来创建按钮图像的方法。它使我能够灵活地更改代码中的参数化外观。它在抽象图形上下文中绘制按钮图像,然后将结果转换为我可以用于按钮的图像。你可能从我的解释中得到足够的信息,你可以根据自己的需要自己尝试一下。

子类UIButton并添加一个CALayer或CAGradientLayer来实现你想要的高亮效果。设置高光层的初始状态为隐藏。用以下命令覆盖setHighlighted::

- (void) setHighlighted:(BOOL)highlight {
    highlightLayer.hidden = !highlight;
    [super setHighlighted:highlight];
}

最新更新