【发布时间】:2012-04-16 00:43:31
【问题描述】:
我想在UIView 上模拟选定UITableViewCell(蓝色)的行为,有没有办法做到这一点,即当用户点击UIView 时,就像点击表格视图单元格一样.该视图将使用相同的蓝色突出显示。
【问题讨论】:
标签: iphone uiview uitableview highlight
我想在UIView 上模拟选定UITableViewCell(蓝色)的行为,有没有办法做到这一点,即当用户点击UIView 时,就像点击表格视图单元格一样.该视图将使用相同的蓝色突出显示。
【问题讨论】:
标签: iphone uiview uitableview highlight
首先看看 UITableView 单元格的行为是很有用的:
UIControlEventTouchUpInisde 控制事件那么我们如何模拟呢?我们可以从子类化UIControl 开始(它本身就是 UIView 的子类)。我们需要继承 UIControl,因为我们的代码需要响应 UIControl 方法sendActionsForControlEvents:。这将允许我们在自定义类上调用addTarget:action:forControlEvents。
TouchHighlightView.h:
@interface TouchHighlightView : UIControl
@end
TouchHighlightView.m:
@implementation TouchHighlightView
- (void)highlight
{
self.backgroundColor = [UIColor blueColor];
}
- (void)unhighlight
{
self.backgroundColor = [UIColor whiteColor];
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
[self highlight];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
[self unhighlight];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
// assume if background color is blue that the cell is still selected
// and the control event should be fired
if (self.backgroundColor == [UIColor blueColor]) {
// send touch up inside event
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
// optional: unlighlight the view after sending control event
[self unhighlight];
}
}
示例用法:
TouchHighlightView *myView = [[TouchHighlightView alloc] initWithFrame:CGRectMake(20,20,200,100)];
// set up your view here, add subviews, etc
[myView addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myView];
这只是一个粗略的开始。随意根据您的需要进行修改。根据其使用情况,可以进行一些改进以使其对用户更好。例如,当 UITableCell 处于选中(蓝色)状态时,请注意 textLabels 中的文本如何变为白色。
【讨论】: