为UIButton以编程方式创建突出显示的状态背景图像

时间:2011-12-08 22:24:51

标签: iphone ios 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;

获得的按钮具有所需的方面,但现在我需要的是,当按钮的状态突出显示时,应该有渐变效果渐渐变为黑色以让用户知道他已按下按钮,因为现在当我按下按钮,视图没有任何反应,因此用户无法知道他按下了按钮。

我想探索一个不涉及为所需状态设置背景图像的选项,因为按钮的文本可以根据应用程序配置动态更改,因此我需要完全按代码执行此操作。

2 个答案:

答案 0 :(得分:0)

Although this won't directly answer your question, it may help.我必须动态地为按钮创建一些图形,并想出一种使用核心图形来创建按钮图像的方法。它使我能够灵活地在代码中以参数化方式更改外观。它在抽象图形上下文中绘制按钮图像,然后将结果转换为可用于我的按钮的图像。你可以从我的解释中得到足够的信息,你可以自己尝试来满足你的需求。

答案 1 :(得分:0)

UIButton子类并添加CALayer或CAGradientLayer以实现您想要的高光效果。将高亮图层的初始状态设置为隐藏。用以下内容覆盖setHighlighted:

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