我有一个UIButton
具有默认图像的图像,以及另一个用于突出显示/选定图像的图像。按下按钮时,按钮的图像变为突出显示,如果 touchUp 在内部,则变为选中。通常的东西.. IB 内的所有设置。
但是,我试图在按钮上设置一个标签,在一个非常棘手的地方(未对齐,硬编码)。
我尝试在 IB 中的按钮上添加标签。问题:我需要标签的文本颜色随着按钮控制状态的变化而变化。
因此,我创建了一个UIButton
子类,添加了一个UILabel
Outlet,并通过覆盖以下方法:
- (void)touchesBegan/Moved/Cancelled/Ended:...;
- (void)setSelected:...
我能够实现我想要的……但是!当我快速单击按钮时,不会反映更改。有时它不能正常工作......我什至使用了异步调用......没用。
于是,我去了UIButton
's titleLabel
。我尝试使用它没有运气。
所以,我试过UIButton setTitle: forState:
了,没用……救命?
额外细节:
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; 如果(自我){ [self.titleLabel setFrame:CGRectMake(0, 0, 100, 100)]; [self.titleLabel setText:@"标题标签"]; [self.titleLabel setHidden:NO]; [self.imageView setAlpha:0.2f]; NSLog(@"%@", self.subviews); [自我设置标题:@“默认!!” forState:UIControlStateNormal]; } 回归自我; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [超级 touchesBegan:touches withEvent:event]; [self performSelector:@selector(check) withObject:nil afterDelay:0.1]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [超级 touchesMoved:touches withEvent:event]; [self performSelector:@selector(check) withObject:nil afterDelay:0.1]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [超级 touchesCancelled:touches withEvent:event]; [self performSelector:@selector(check) withObject:nil afterDelay:0.1]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [超级 touchesEnded:touches withEvent:event]; [self performSelector:@selector(check) withObject:nil afterDelay:0.1]; } - (void)setSelected:(BOOL)selected { [超级setSelected:selected]; [self performSelector:@selector(check) withObject:nil afterDelay:0.1]; } -(无效)检查{ if (self.isSelected || self.state == UIControlStateHighlighted || self.state == UIControlStateSelected) { [_label setHighlighted:YES]; } 别的 { [_label setHighlighted:NO]; } }
输出:
(
"<UIImageView: 0x8b24930; frame = (0 0; 243 39); clipsToBounds = YES; alpha = 0.2; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x8b248e0>>",
"<UIButtonLabel: 0x8b247a0; frame = (0 0; 100 100); text = 'THE TITLE LABEL'; clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x8b25000>>"
)