[英]How to handle touch event on UILabel as subview of UITableViewCell?
我的應用程序有一個自定義UITableView
。 在其UIViewController
的cellForRowAtIndexPath
委托方法中,我將包含多個自定義 UILabel(實際上是OHAttributedLabel
的子類)的自定義UITableViewCell
對象實例化為內容視圖的子視圖。
我嘗試在 label 上設置userInteractionEnabled = YES
,然后在視圖 controller 中添加觸摸事件,但這不起作用。
想法?
謝謝
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if (CGRectContainsPoint([self.site frame], [touch locationInView:self.view])){
//do whatever you want
}
}
或者
UILabel *label = =[UILabel alloc]init];
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)] autorelease];
[label addGestureRecognizer:tapGesture];
OHAttributedLabel 中的問題。 這個 label 還可以處理點擊鏈接。 因此,對於 label(不僅僅是鏈接)的任何點的手柄點擊,您必須
self.textLabel.onlyCatchTouchesOnLinks = NO;
self.textLabel 是您的 OHAttributedLabel。 並且不要忘記 userInteractionEnabled。
UILabel 不是 UIControl,因此您不會在 UIControlEventTouchUpInside 或類似上獲得事件。 為什么不使用按鈕呢? 您可以讓它看起來與 label 完全一樣。
無論如何,您可能需要在 cellForRowAtIndexPath: 方法中的 UIButton 上設置 addTarget:action:forControlEvents: 和標簽。 在該方法中,通過檢查標記值來檢測點擊了哪個單元格的按鈕。
如果您必須使用 UILabel,那么您需要對其進行子類化並攔截 touchesBegan/touchesEnded 方法(從 UIResponder 繼承)來檢測自己的 UIControlEventTouchUpInside。
我不知道是不是同樣的問題,但是......我添加了一個 label 並且無法讓它識別觸摸,我最終意識到這是因為我將它添加為子視圖,但它的框架在它之外父母的框架,因此觸摸層次結構破裂
我只是在使用 static 表格單元格作為設置表格時遇到了問題,我希望整個單元格觸發單元格文本字段的第一響應者。
在沒有使用手勢識別器進行任何觸摸后,我最終在 label(觸摸禁用)和文本字段后面添加了一個透明(自定義、空白標題)按鈕。 我認為它應該以更優雅的方式工作,但它解決了現在的任務和有限的目的。 (您可以從按鈕的默認操作中拖動連接)
有點丑。 再說一次,它只是描述了文本字段后面對觸摸做出反應的區域。 畢竟這是本意。 所以也許它只是沒有那么花哨。
將保留它,直到我找到識別器不觸發的原因。
您可以使用TTTAttributedLabel
來代替它。 這很容易。 當您初始化 UITableViewCell 時,您可以委托:TTTAttributedLabelDelegate,例如:
@interface MyTableViewCell : UITableViewCell<TTTAttributedLabelDelegate>{
UILabel *nameLabel;
TTTAttributedLabel *valueLabel;
}
初始時,您可以添加指向 label 的鏈接:
[valueLabel addLinkToPhoneNumber:valueStr withRange:NSMakeRange(0, valueStr.length)];
所以,你可以做任何你想做的事:
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber{
//do anything you want.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.