Нажмите "Жест" на части UILabel
Я мог бы успешно добавить жесты привязки к части UITextView со следующим кодом:
UITextPosition *pos = textView.endOfDocument;// textView ~ UITextView
for (int i=0;i<words*2-1;i++){// *2 since UITextGranularityWord considers a whitespace to be a word
UITextPosition *pos2 = [textView.tokenizer positionFromPosition:pos toBoundary:UITextGranularityWord inDirection:UITextLayoutDirectionLeft];
UITextRange *range = [textView textRangeFromPosition:pos toPosition:pos2];
CGRect resultFrame = [textView firstRectForRange:(UITextRange *)range ];
UIView* tapViewOnText = [[UIView alloc] initWithFrame:resultFrame];
[tapViewOnText addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(targetRoutine)]];
tapViewOnText.tag = 125;
[textView addSubview:tapViewOnText];
pos=pos2;
}
Я хочу подражать тому же поведению в UILabel
. Проблема в том, что UITextInputTokenizer
(используется для обозначения отдельных слов) объявляется в UITextInput.h
, и только UITextView
и UITextField
соответствуют UITextInput.h
; UILabel
нет.
Есть ли обходной путь для этого?
Ответы
Ответ 1
Вы можете попробовать https://github.com/mattt/TTTAttributedLabel и добавить ссылку на ярлык. Когда ссылка нажата, вы получаете действие, поэтому часть ярлыка нажимает только то, что вам нужно, чтобы настроить ссылку на метку. Я пробовал это в прошлом, и он работал безупречно, но мой клиент не интересовался использованием стороннего компонента, поэтому дублировал эту функцию с помощью UIWebView и HTML.
Ответ 2
Попробуйте это. Пусть ваша метка label
:
//add gesture recognizer to label
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] init];
[label addGestureRecognizer:singleTap];
//setting a text initially to the label
[label setText:@"hello world i love iphone"];
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGRect rect = label.frame;
CGRect newRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width/2, rect.size.height);
if (CGRectContainsPoint(newRect, touchPoint)) {
NSLog(@"Hello world");
}
}
Нажатие на первую половину метки будет работать (это дает выход журнала). Не вторая половина.
Ответ 3
Один из вариантов - использовать не редактируемый UITextView вместо UILabel. Конечно, это может быть или не быть подходящим решением в зависимости от ваших конкретных потребностей.
Ответ 4
Вот небольшая библиотека, специально для ссылок в UILabel FRHyperLabel.
Чтобы добиться такого эффекта:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicleula justo. Нам в urna neque. Maecenas в полете eu sem porta dictum nec vel tellus.
используйте код:
//Step 1: Define a normal attributed string for non-link texts
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
//Step 2: Define a selection handler block
void(^handler)(FRHyperLabel *label, NSString *substring) = ^(FRHyperLabel *label, NSString *substring){
NSLog(@"Selected: %@", substring);
};
//Step 3: Add link substrings
[label setLinksForSubstrings:@[@"Lorem", @"Pellentesque", @"blandit", @"Maecenas"] withLinkHandler:handler];
Ответ 5
Это базовый код для того, как добавить UITapGestureRecognizer
к вашему управлению;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[MyLabelName addGestureRecognizer:singleTap];
[self.view addSubView:MyLabelName]
Это метод, который вызывается при нажатии на MyLabelName
;
-(void)handleSingleTap:(UILabel *)myLabel
{
// do your stuff;
}