我正在创建一个类似于Facebook的新闻提要。 当用户点击Facebook新闻提要上的某个名字时,当手指向下时,该名称会以灰色背景突出显示。当抬起手指时,高光消失。
我怎样才能做到这一点?
在
UIResponder的任何子类中实现以下函数(例如在UIViewController中)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
通过触摸判断触摸是否在UILabel内部[0].locationInView(yourUILabel)
你可以
试试这个
[button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:UIControlStateHighlighted];
imageWithColor 看起来像这样:
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
我建议一种适合您工作的不同方法。我建议你简单地添加一个按钮,该按钮具有标签的宽度和高度,并使其透明。然后将标签添加为子视图。使用按钮的点击事件,您可以更改标签的颜色,从而突出显示它。请参阅下面我的示例。
- (void)viewDidLoad {
[super viewDidLoad];
//have a property named label
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
[_label setText:@"LABEL"];
[_label setBackgroundColor:[UIColor redColor]];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(0, 0, 100, 50)];
[button addTarget:self action:@selector(tapDown) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(tapCancel) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(tapCancel) forControlEvents:UIControlEventTouchUpOutside];
[self.view addSubview:button];
[button addSubview:_label];
}
-(void)tapDown{
_label.backgroundColor=[UIColor blueColor];
}
-(void)tapCancel{
_label.backgroundColor=[UIColor redColor];
}