2012-04-16 11 views

答えて

4

まず、それはのUITableView細胞がどのように動作するかを見て便利です:

場合はタッチが進行
  • している間にセルが青色の背景色の変更に触れ、青のままです
    • の場所タッチが動いたとき(つまり、ユーザーが指を動かしているとき)、セルの背景が白に戻ります。
    • タッチの位置を変更せずにセルにタッチして指を持ち上げた場合、コントロールイベントが発生します

    これをどのようにシミュレートできますか?まず、サブタイトルUIControl(それ自体はUIViewのサブクラスです)から始めることができます。私たちのコードはUIControlメソッドsendActionsForControlEvents:に応答する必要があるので、UIControlをサブクラス化する必要があります。これにより、カスタムクラスで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のテキストがどのように白に変わるかを確認します。

  • +0

    すばらしい、ありがとう@jonkroll! – tom