我正在使用 TTTAttributedLabel 添加指向标签部分的链接。我希望链接调用选择器(同一文件中的方法),而不是 Web URL。
有可能吗,如何?
您可以使用自己的 url 方案创建链接,例如<a href="myScheme://mySelector1"
在UIWebView
委托上只需捕获此重定向
NSString * const kMyURLScheme = @"myScheme";
NSString * const kMySelector = @"mySelector1";
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navi
gationType:(UIWebViewNavigationType)navigationType {
if ([[request.URL scheme] isEqualToString:kMyURLScheme]) {
SEL mySel = NSSelectorFromString([URL host]); // Do something with @selector
return NO; // remember to return NO to denie `UIWebView` execute your request
}
我已经使用UILabel
了 TTTAttributedLabel 来代替。此代码也可能适用于它:
[label addGestureRecognizer:singleTap];
[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);
CGRect newRect2 = CGRectMake(rect.origin.x+rect.size.width/2, rect.origin.y, rect.size.width/2, rect.size.height);
if (CGRectContainsPoint(newRect, touchPoint)) {
[self performSelector:@selector(printMessage:) withObject:@"First half of label touched"];
}
else if (CGRectContainsPoint(newRect2, touchPoint)) {
[self performSelector:@selector(printMessage:) withObject:@"Second half of label touched"];
}
}
-(void) printMessage:(NSString *)message
{
NSLog(@"%@",message);
}
我需要做的就是在: ... 方法的delegate
方法中添加行为。TTTAttributedLabel
didSelectLink