我知道UITextView默认可以检测到URL,但是如何让它检测到hashtags(#)?

它不需要在键入时检测主题标签,但是然后viewDidLoad文本在UITextView中设置,所以我想将主题标签检测为颜色或其他东西.

我一直在使用ActiveLabel,但这只适用于UILabel,我需要UITextView具有的滚动功能.

解决方法

这应该适合你

>使用任何名称创建一个新的swift文件(UITextViewHashtagExtension.swift)
>在下面插入以下代码:

import UIKit

extension UITextView {

func resolveHashTags(){

    // turn string in to Nsstring
    let nsText:Nsstring = self.text

    // this needs to be an array of Nsstring.  String does not work.
    let words:[Nsstring] = nsText.componentsSeparatedByString(" ")

    // you can't set the font size in the storyboard anymore,since it gets overridden here.
    let attrs = [
        NSFontAttributeName : UIFont.systemFontOfSize(17.0)
    ]

    // you can staple URLs onto attributed strings
    let attrString = NSMutableAttributedString(string: nsText as String,attributes:attrs)

    // tag each word if it has a hashtag
    for word in words {

        // found a word that is prepended by a hashtag!
        // homework for you: implement @mentions here too.
        if word.hasPrefix("#") {

            // a range is the character position,followed by how many characters are in the word.
            // we need this because we staple the "href" to this range.
            let matchRange:NSRange = nsText.rangeOfString(word as String)

            // convert the word from Nsstring to String
            // this allows us to call "dropFirst" to remove the hashtag
            var stringifiedWord:String = word as String

            // drop the hashtag
            stringifiedWord = String(stringifiedWord.characters.dropFirst())

            // check to see if the hashtag has numbers.
            // ribl is "#1" shouldn't be considered a hashtag.
            let digits = NSCharacterSet.decimalDigitCharacterSet()

            if let numbersExist = stringifiedWord.rangeOfCharacterFromSet(digits) {
                // hashtag contains a number,like "#1"
                // so don't make it clickable
            } else {
                // set a link for when the user clicks on this word.
                // it's not enough to use the word "hash",but you need the url scheme Syntax "hash://"
                // note:  since it's a URL Now,the color is set to the project's tint color
                attrString.addAttribute(NSLinkAttributeName,value: "hash:\(stringifiedWord)",range: matchRange)
            }

        }
    }

    // we're used to textView.text
    // but here we use textView.attributedText
    // again,this will also wipe out any fonts and colors from the storyboard,// so remember to re-add them in the attrs dictionary above
    self.attributedText = attrString
}

}

要使用它,您可以执行以下操作:

self.textView.text = "This is an #example test"
self.textView.resolveHashTags()

针对Swift 4.0进行了更新:

extension UITextView {

    func resolveHashTags() {

        // turn string in to Nsstring
        let nsText = Nsstring(string: self.text)

        // this needs to be an array of Nsstring.  String does not work.
        let words = nsText.components(separatedBy: CharacterSet(charactersIn: "#ABCDEFGHIJKLMnopQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_").inverted)

        // you can staple URLs onto attributed strings
        let attrString = NSMutableAttributedString()
        attrString.setAttributedString(self.attributedText)

        // tag each word if it has a hashtag
        for word in words {
            if word.count < 3 {
                continue
            }

            // found a word that is prepended by a hashtag!
            // homework for you: implement @mentions here too.
            if word.hasPrefix("#") {

                // a range is the character position,followed by how many characters are in the word.
                // we need this because we staple the "href" to this range.
                let matchRange:NSRange = nsText.range(of: word as String)

                // drop the hashtag
                let stringifiedWord = word.dropFirst()
                if let firstChar = stringifiedWord.unicodeScalars.first,NSCharacterSet.decimalDigits.contains(firstChar) {
                    // hashtag contains a number,like "#1"
                    // so don't make it clickable
                } else {
                    // set a link for when the user clicks on this word.
                    // it's not enough to use the word "hash",but you need the url scheme Syntax "hash://"
                    // note:  since it's a URL Now,the color is set to the project's tint color
                    attrString.addAttribute(NSAttributedStringKey.link,range: matchRange)
                }

            }
        }

        // we're used to textView.text
        // but here we use textView.attributedText
        // again,// so remember to re-add them in the attrs dictionary above
        self.attributedText = attrString
    }
}

ios – 如何让UITextView检测主题标签?的更多相关文章

  1. Html5跳转到APP指定页面的实现

    这篇文章主要介绍了Html5跳转到APP指定页面的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. ios – 比较两个版本号

    如何比较两个版本号字符串?例如:3.1.1和3.1.2.5.4现在我需要找出3.1.2.5.4是否高于3.1.1但我不知道如何做到这一点.有谁能够帮我?

  3. iOS:无法获取Caches目录的内容

    试图获取Caches目录的内容:路径是正确的,我可以在Finder中看到它存在并包含我的文件.directoryItems是nil,错误是我怎么了?解决方法你使用错误的路径.要为应用程序获取正确的缓存目录,请使用此:在cacheDirectory中,您将收到这样的字符串路径:整个代码:

  4. ios – Reactive Cocoa – 以编程方式设置文本时不会调用UITextView的rac_textSignal

    我正在实现一个聊天UI,并使用ReactiveCocoa根据用户的类型调整聊天气泡的大小.目前,我正在基于textview的rac_textSignal更新UI的布局.一切都很好–除了一点:当用户发送消息时,我以编程方式清除文本字段:…我是否需要拥有一个持有currentTypedString的Nsstring,并在该字符串更新时驱动UI更改?

  5. ios – 如何使用CNContactVCardSerialization dataWithContacts:方法获取联系人图像的VCF数据?

    我正在使用CNContacts和CNContactUI框架并通过此选择联系人和此联系对象具有contact.imageData和日志.但当我试图通过交叉检查这些数据这是空的:为什么我收到此null并且此联系人在签入联系人时有图像?

  6. ios – 签名无效:oauth_signature

    我正在尝试生成oauth_signature以使用FatsecretAPI,但是获得无效的签名错误–无法弄清楚原因.我尝试尽可能准确地遵循here所述的所有步骤(参见步骤2)来生成签名值.他们说:UsetheHMAC-SHA1signaturealgorithmasdefinedbythe[RFC2104]tosigntherequestwheretextistheSignatureBaseStr

  7. ios – 在没有alloc init的情况下将NSString转换为NSAttributedString

    解决方法我建议在Nsstring上创建一个类别,使用一种方法将其转换为NSAttributedString,然后在整个项目中使用该辅助方法.像这样:

  8. ios – 确定图像选择器媒体类型是否为视频

    优选地,包括“所有图像类型”或“所有视频类型”的方式.解决方法最好检查一下与特定UTI的一致性.现在,iOS告诉你它是一个public.movie,但它明年会说些什么呢?你会看到有人检查public.video.太棒了,所以你硬编码了两种而不是一种.但问“这是一部电影吗?”而不是硬编码您认为iOS将返回的特定类型?

  9. ios – 使用NSURLSession获取JSON数据

    我试图从谷歌距离api使用NSURLSession获取数据,但如下所示,当我打印响应和数据时,我得到的结果为NULL.可能是什么问题?

  10. xcode – 如何在调试中查看NSString中的文本

    我是XCode4的新手,我无法弄清楚如何在断点中查看变量(如NSCFString)的值.我看到我的Autos/Local但它们显示Hex值并且SummaryUnavailable.我想要做的就是将字符串本身视为常规文本.我甚至徘徊在变量上,期望在VisualStudio中看到他们的价值而没有运气.解决方法打开调试器的控制台视图,并在提示符下键入:要么

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部