微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift实现微博@及#话题#功能




在微博信息流中点击@某人然后跳转到某人的主页,以及点击话题跳到相关话题页,类似于HTML中的文本链接,在iOS中实现方法也差不多,也是往文本中添加文本链接的方式,具体看以下代码


let text:String = "#证人杨幂发福利# 电影《我是证人》#福利#即将在2015-10-25上映咯!转发@电影我是证人 地址(http://www.baidu.com)@杨幂 哟~"
        let attributedString:NSMutableAttributedString = NSMutableAttributedString(string:text)
        let textRange = NSRange(location: 0,length: text.length)
        
        //规则检查
        var ranges:[NSRange] = []
        //话题(使用正则匹配出#话题#所在位置)
        var reg = try? NSRegularExpression(pattern: "#.+?#",options: [])
        reg?.enumerateMatchesInString(text,options: [],range: textRange,usingBlock: {result,flags,ptr in
            if let result = result
            {
                ranges.append(result.range)
            }
        })
        //然后给话题所在的文本添加链接
        for range in ranges
        {
            let subject = (text as Nsstring).substringWithRange(range)
            attributedString.addAttribute(NSLinkAttributeName,value: "yourapp://subject?text=\(subject.URLEncoded)",range: range)
        }
        
        //@某人
        ranges.removeAll()
        reg = try? NSRegularExpression(pattern: "@[^\\s]+",ptr in
            if let result = result
            {
                ranges.append(result.range)
            }
        })
        for range in ranges
        {
            let subject = (text as Nsstring).substringWithRange(range)
            attributedString.addAttribute(NSLinkAttributeName,value: "yourapp://mind?name=\(subject.URLEncoded)",range: range)
        }
        
        //文本框
        let textView:UITextView = UITextView()
        textView.editable = false
        textView.frame = CGRectMake(20,10,view.frame.width - 20,150)
        textView.attributedText = attributedString
        textView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blueColor()]
        
        view.addSubview(textView)

//在此统一处理

func application(application: UIApplication,openURL url: NSURL,sourceApplication: String?,annotation: AnyObject) -> Bool
    {
        //在此处理相关链接
        //openURL:yourapp://mind?name=%40%E6%9D%A8%E5%B9%82,scheme:yourapp,query:Optional("name=%40%E6%9D%A8%E5%B9%82")
        print("openURL:\(url),scheme:\(url.scheme),query:\(url.query)")
        return true
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐