在UITableView的 didSelectRowAtIndexPath中獲取點擊區域


項目中,要在UITableViewCell區分不同的點擊區域,比如左邊點擊執行某個操作,右邊點擊執行另一個操作。原本我的方案是在cell的左邊和右邊各放一個透明的UIButton,點擊兩個button執行不同的操作,而controller中的didSelectRowAtIndexPath函數就設為空了。但是后來有個問題,就是可以同時用多個手指長按在不同的cell上,導致觸發過個操作,而且cell的選中態也不好控制。

 

后來想到,UIview的觸摸事件可以得到觸摸的位置,那可不可以在cell的touch事件中得到位置,保存到一個變量中,然后didSelectRowAtIndexPath函數再根據這個變量執行不同的操作呢?

代碼如下:

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch* touch = [[event allTouches] anyObject];
    CGPoint leftLocation = [touch locationInView: _bgViewLeft];
    CGPoint rightLocation = [touch locationInView: _bgViewRight];
    
    if ([_bgViewLeft pointInside:leftLocation withEvent:event])
    {
        self.touchLocation = eCellTouchLocationLeft;
        
        [super touchesBegan:touches withEvent:event];
    }
    else if ([_bgViewRight pointInside:rightLocation withEvent:event])
    {
        self.touchLocation = eCellTouchLocationRight;
        
        [super touchesBegan:touches withEvent:event];
    }
    else
    {
        self.touchLocation = eCellTouchLocationALL;
        
        [super touchesBegan: touches withEvent:event];
    }
}

 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UPAboutMeTableViewCell *cell = (UPAboutMeTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if (cell.touchLocation == eCellTouchLocationLeft || cell.touchLocation == eCellTouchLocationALL)
    {
        [self aboutMeTableViewCellonDidClickInLeft:cell];
    }
    else
    {
        [self aboutMeTableViewCellonDidClickInRight:cell];
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM