当我点击已经选中的按钮时,我希望我的UIButton显示突出显示的状态。
基本上在突出显示的状态下,我将* .png图像应用为我的UIButton背景图像,以提供按下的效果。
但是如果按钮已经处于选中状态当我再次点击它时,我看不到突出显示的状态,但它直接进入正常状态!
观看问题 - > Video of the Issue!
请帮忙
//0 init UIButton
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, aSide, aSide)];
//1 Give it a backgroundColor
[button setBackgroundColor:aColor];
[..]
//2 Set titleLabel and its style
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
UIImage *shadowImage = [UIImage imageNamed:kBtnShadow];
shadowImage = [shadowImage stretchableImageWithLeftCapWidth:floorf(shadowImage.size.width/2) topCapHeight:floorf(shadowImage.size.height/2)];
[button setBackgroundImage:shadowImage forState: UIControlStateHighlighted];
[button setTitle:aLabel forState: UIControlStateNormal];
//3 Assign tag and Action
[button setTag:tag];
[button addTarget:target action:a forControlEvents:UIControlEventTouchUpInside];
各种状态:UIControlStateNormal
,UIControlStateSelected
和(UIControlStateSelected | UIControlStateHighlighted)
都是截然不同的。如果您希望shadowImage
同时应用于(仅)突出显示状态和突出显示的+选定状态,则还必须设置:
[button setBackgroundImage:shadowImage forState:(UIControlStateHighlighted | UIControlStateSelected)]
在swift
,这将是:
button.setBackgroundImage(shadowImage, forState: UIControlState.Selected.union(UIControlState.Highlighted))
在Swift v3(2016年11月)中:
button.setBackgroundImage(shadowImage, for: UIControlState.selected.union(UIControlState.highlighted))
Swift 4.2
仅适用于编程方式。
aButton.setImage(UIImage(named: "your_image"), for: [.selected, .highlighted])