Я пытаюсь сделать UILabel
ссылкой на UIWebView
. Как я могу сделать UILabel
работать как гиперссылка?Objective-C UILabel как HyperLink
ответ
Вы можете пойти на UITapGestureRecognizer, что будет работать что-то подобное, что вы хотите -
UILabel *myLabel = [[UILabel alloc] initWithFrame:];//Define label here as per needs
myLabel.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myAction:)];
[myLabel addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;
gr.cancelsTouchesInView = NO;
[self.view addSubview:myLabel];
Теперь для действий -
- (void) myAction: (UITapGestureRecognizer *) gr {
// Define actions here
}
Возможным решением является использование UIButton
с типом UIButtonTypeCustom
вместо UILabel
. Он похож на ярлык и доступен для просмотра.
Вы также можете рассмотреть сторонние реализации, такие как TTLabel three20 и Fancy UILabels.
Благодарим за помощь. :) –
Вы просто проверите эту ссылку, это будет полезно для you.try один раз и сообщите нам, если это вам поможет.
how to make a specific word touchable for its meaning in a text?
Спасибо. Это полезно. –
Еще раз спасибо. Теперь я думаю, что могу делать UILabel/Hyperlink несколькими способами. Я нашел ответ rishi более простым в использовании в качестве новичка. –
ya Я знаю, что применять прикосновение и жест - самый простой способ. ok Как ваше желание просто доступно для помощи не для вашей репутации. – vishiphone
Я нашел некоторый код в гиперссылке UILabe. .. Надеемся, что это будет полезно: Источник: http://sickprogrammersarea.blogspot.in/2014/03/adding-links-to-uilabel.html
#import "ViewController.h"
#import "TTTAttributedLabel.h"
@interface ViewController()
@end
@implementation ViewController
{
UITextField *loc;
TTTAttributedLabel *data;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 20, 80, 25) ];
[lbl setText:@"Text:"];
[lbl setFont:[UIFont fontWithName:@"Verdana" size:16]];
[lbl setTextColor:[UIColor grayColor]];
loc=[[UITextField alloc] initWithFrame:CGRectMake(4, 20, 300, 30)];
//loc.backgroundColor = [UIColor grayColor];
loc.borderStyle=UITextBorderStyleRoundedRect;
loc.clearButtonMode=UITextFieldViewModeWhileEditing;
//[loc setText:@"Enter Location"];
loc.clearsOnInsertion = YES;
loc.leftView=lbl;
loc.leftViewMode=UITextFieldViewModeAlways;
[loc setDelegate:self];
[self.view addSubview:loc];
[loc setRightViewMode:UITextFieldViewModeAlways];
CGRect frameimg = CGRectMake(110, 70, 70,30);
UIButton *srchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
srchButton.frame=frameimg;
[srchButton setTitle:@"Go" forState:UIControlStateNormal];
[srchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
srchButton.backgroundColor=[UIColor clearColor];
[srchButton addTarget:self action:@selector(go:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:srchButton];
data = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(5, 120,self.view.frame.size.width,200) ];
[data setFont:[UIFont fontWithName:@"Verdana" size:16]];
[data setTextColor:[UIColor blackColor]];
data.numberOfLines=0;
data.delegate = self;
data.enabledTextCheckingTypes=NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber;
[self.view addSubview:data];
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
{
NSString *val=[[NSString alloc]initWithFormat:@"%@",url];
if ([[url scheme] hasPrefix:@"mailto"]) {
NSLog(@" mail URL Selected : %@",url);
MFMailComposeViewController *comp=[[MFMailComposeViewController alloc]init];
[comp setMailComposeDelegate:self];
if([MFMailComposeViewController canSendMail])
{
NSString *recp=[[val substringToIndex:[val length]] substringFromIndex:7];
NSLog(@"Recept : %@",recp);
[comp setToRecipients:[NSArray arrayWithObjects:recp, nil]];
[comp setSubject:@"From my app"];
[comp setMessageBody:@"Hello bro" isHTML:NO];
[comp setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:comp animated:YES completion:nil];
}
}
else{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:val]];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if(error)
{
UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"Erorr" message:@"Some error occureed" delegate:nil cancelButtonTitle:@"" otherButtonTitles:nil, nil];
[alrt show];
[self dismissViewControllerAnimated:YES completion:nil];
}
else{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithPhoneNumber:(NSString *)phoneNumber
{
NSLog(@"Phone Number Selected : %@",phoneNumber);
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:@"iPhone"]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNumber]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Your device doesn't support this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[Notpermitted show];
}
}
-(void)go:(id)sender
{
[data setText:loc.text];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"Reached");
[loc resignFirstResponder];
}
- 1. NumberFormatter - ObjectiveC
- 2. ObjectiveC NSURLSessionDownloadTask
- 3. Javascript - Div Box как HyperLink + Вложенный текст HyperLink - возможно?
- 4. Dynamic HyperLink
- 5. hyperlink styling
- 6. Проблема HyperLink
- 7. Как добавить HyperLink в ModelState.AddModelError
- 8. Как добавить HyperLink с JsPDF?
- 9. Объединить строки в ObjectiveC
- 10. Curl, Asana & ObjectiveC
- 11. ObjectiveC Синтаксис определения функции
- 12. NSString вопрос в ObjectiveC
- 13. ObjectiveC, создавая массив классов
- 14. AudioQueue iOS ObjectiveC
- 15. Вычисление пересечения в ObjectiveC
- 16. ObjectiveC - конструктор, управление памятью
- 17. MulticastDelegate in ObjectiveC
- 18. Передача переменных в ObjectiveC
- 19. от ObjectiveC до ECMAscript
- 20. ObjectiveC на CAShapeLayer
- 21. Статическая переменная в ObjectiveC
- 22. JSON ObjectiveC - Ошибка
- 23. ObjectiveC Sorting Array
- 24. Назначение ObjectiveC и init?
- 25. Организация проекта ObjectiveC
- 26. Настоящий небольшой ModalVIewController ObjectiveC
- 27. ObjectiveC - [self.view viewWithTag] возврат
- 28. ObjectiveC блокирует эквивалент Java
- 29. Быстрая версия макроса ObjectiveC
- 30. Отключение определенной задачи ObjectiveC?
Это на самом деле то, что я пытаюсь сделать. Спасибо. –