【问题标题】:How to simulate the UITableviewCell section on a UIView?如何模拟 UIView 上的 UITableviewCell 部分?
【发布时间】:2012-04-16 00:43:31
【问题描述】:

我想在UIView 上模拟选定UITableViewCell(蓝色)的行为,有没有办法做到这一点,即当用户点击UIView 时,就像点击表格视图单元格一样.该视图将使用相同的蓝色突出显示。

【问题讨论】:

    标签: iphone uiview uitableview highlight


    【解决方案1】:

    首先看看 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 中的文本如何变为白色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      相关资源
      最近更新 更多