[英]How to detect which UILabel was tapped?
我有三個UILabels。 我想檢測哪個標簽是Tapped,然后檢索該標簽的字符串值 。 這就是我的嘗試,我只能設法檢測輕敲的位置,但我無法檢測到哪個標簽被點擊。
標簽創建
for (NSInteger i=1; i<=[pdfs count]; i++){
UILabel *newLabel=[[UILabel alloc] init];
newLabel.text = [NSString stringWithFormat:[[pdfs objectAtIndex:(i-1)] lastPathComponent]];
newLabel.frame = CGRectMake(10, 60*i, 320, 20);
newLabel.tag=i;
newLabel.font = [UIFont systemFontOfSize:20.0f];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.userInteractionEnabled = YES;
[self.view addSubview:newLabel];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[newLabel addGestureRecognizer:singleTap];
[newLabel release], newLabel=nil;
[singleTap release];
}
檢測水龍頭
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location;
location = [recognizer locationInView:self.view];
NSString *documentName;
if(location.y<150.0){
documentName = [[pdfs objectAtIndex:0] lastPathComponent];
}
else{
documentName = [[pdfs objectAtIndex:1] lastPathComponent];
}
UIGestureRecognizer引用了它所附加的視圖,因此您可以從中獲取標簽的標簽:
int touchedtag = recognizer.view.tag;
documentName = [[pdfs objectAtIndex:touchedtag-1] lastPathComponent];
手勢識別器知道它屬於哪個視圖。
UIView *theView = recognizer.view;
// cast it to UILabel if you are sure it is one
UILabel *theLabel = (UILabel *)theView;
正如您在標簽上添加GestureRecognizer
// called when touch is began or when user touches
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
UILabel *theLabel = (UILabel *)touch.view;
if (theLabel.tag == 1)
{}
else if ...
}
為什么要將標簽用作按鈕? 只需使用按鈕,就可以將它們配置為看起來就像標簽一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.