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

前端之家收集整理的这篇文章主要介绍了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
    }

猜你在找的Swift相关文章