当我点击 UIButton 时,我希望它更改其文字颜色。此外,我在每个按钮下方设置了一个视图,按钮的下边距为7.我已经完成了这一操作,以便通过更改视图的背景颜色来点击按钮的高亮效果。点击按钮没有任何结果。这里附上截图
我希望它在点击时完全像这样
- (IBAction)setMenubtn:(UIButton *)menubtn:(id)sender {
[self.menubtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.contactsbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.favoritesbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.topView setBackgroundColor:[UIColor colorWithRed:2/255 green:115/255 blue:168/255 alpha:1]];
[self.topview2 setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
[self.topview3 setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
}
- (IBAction)setContactsbtn:(UIButton *)contactsbtn:(id)sender {
[self.menubtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.contactsbtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.favoritesbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.topView setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
[self.topview2 setBackgroundColor:[UIColor colorWithRed:2/255 green:115/255 blue:168/255 alpha:1]];
[self.topview3 setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
}
- (IBAction)setFavoritesbtn:(UIButton *)favoritesbtn:(id)sender {
[self.menubtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.contactsbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.favoritesbtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.topView setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
[self.topview2 setBackgroundColor:[UIColor colorWithRed:226/255 green:226/255 blue:226/255 alpha:1]];
[self.topview3 setBackgroundColor:[UIColor colorWithRed:2/255 green:115/255 blue:226/255 alpha:1]];
}
显示此输出
答案 0 :(得分:0)
请尝试使用此代码向您展示如何在单击时更改UIButton颜色:
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setSelected:YES];
button.frame = CGRectMake(x, y, width, height);
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[button setTitle:@"Button Title" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"buttonActive.png"] forState:UIControlStateHighlighted];
答案 1 :(得分:0)
为什么要做硬编码。在Github已经制作了这种类型的自定义控件。 您可以根据需要自定义布局,并且易于实现。
答案 2 :(得分:0)
如果按钮不是IBOutlets或连接到情节提要中的按钮,则您的代码将无法更改属性,例如self.menubtn。
确保IBOutlets仅连接一次。
确保IBAction只连接一次并连接到正确的按钮,例如touchUpInside