2012-04-16 35 views
1

我想模擬在UIView上選定的UITableViewCell(藍色)的行爲,有沒有辦法做到這一點,即當用戶點擊UIView時,就像在桌面視圖單元上點擊一樣。該視圖將使用相同的藍色突出顯示。如何模擬UIView上的UITableviewCell部分?

回答

4

首先,它看一個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中的文本如何變爲白色。

+0

精彩,謝謝@jonkroll! – tom 2012-04-16 04:57:54