how to make #key and @key clickable in IOS7

回眸只為那壹抹淺笑 提交于 2019-12-05 01:30:29

问题


Anyone knows how I can make the #KEY and @NAME clickable in the text of comments in IOS7 (the same way that instagram does it for example)? i am trying to use NSMutableAttributedString but I'm not sure how to detect click event, in the image below clicking @Username should take the user to the profile of the user


回答1:


Looking at the UITextViewDelegate protocol, there is a new method in iOS7: textView:shouldInteractWithURL:inRange:.

You didn't share any code, but it is safe to assume you have an attributedString and a range representing the area you turned blue. I'll also assume you can extract the username into a variable called username.

With these three pieces of information, you add a link attribute to that range.

[attributedString addAttribute:NSLinkAttributeName
                         value:[@"username://" stringByAppendingString:username]
                         range:range];

In your delegate, you could do something like this:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([URL.scheme isEqualToString:@"username"]) {
        [self doSomethingWithUserName:URL.host];
        return NO;
    }

    return YES;
}

I believe they demoed this in the Introducing Text Kit session at WWDC 2013.




回答2:


You can use HTML links and render it using UIWebView

<div> Here goes the text. <a href="/users/Username">@Username</a> <a href="/tags/mytag">#mytag</a>. </div>

When a user clicks a link, the web view's delegate method webView:shouldStartLoadWithRequest:navigationType: is called. There you can get the URL from the request and do whatever you want. It's important to return NO from this method, otherwise the web view tries to load the request.




回答3:


You could look at using DTCoreText which offers link buttons what you can add to attributed text. It's based around HTML parsing so you'll need to do a little extra work with the parsing to determine where the link buttons should go.

Alternatively you could add a pat gesture recognizer to the comment view. When a tap is detected you can use <UITextInput> to find out what text was tapped on and if it is a 'link'.



来源:https://stackoverflow.com/questions/19299556/how-to-make-key-and-key-clickable-in-ios7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!