2015-11-30 32 views
1

我有一個UITextField,用戶可以在其中撰寫描述。檢測#標籤並添加到數組

例如:「這是我的#車的圖像,也是我的#fans的一個很酷的#sunshine背景。」

如何檢測「汽車」,「陽光」和「粉絲」的hashtags,並將它們添加到數組中?

+1

怎麼樣'#fans'? –

+0

@BartłomiejSemańczyk - 是的,我忘記了,但你仍然明白我的觀點? –

+0

閱讀此鏈接:http://stackoverflow.com/questions/24359972/detect-hash-tags-mention-tags-in-ios-like-in-twitter-app –

回答

3
let frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 30.0) 

let description = UITextField(frame: frame) 
description.text = "This is a image of my #car. A cool #sunshine background also for my #fans." 


extension String { 
    func getHashtags() -> [String]? { 
     let hashtagDetector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpressionOptions.CaseInsensitive) 
     let results = hashtagDetector?.matchesInString(self, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, self.utf16.count)).map { $0 } 

     return results?.map({ 
      (self as NSString).substringWithRange($0.rangeAtIndex(1)) 
     }) 
    } 
} 

description.text?.getHashtags() // returns array of hashtags 

來源:https://github.com/JamalK/Swift-String-Tools/blob/master/StringExtensions.swift

+0

沒有理由需要使用第三方件垃圾可以很容易地在本地生產。 – Loxx

+0

這是使用正則表達式查找這些項目後需要「散列標籤」sh * t的兩個調用。我永遠不會理解你爲什麼需要使用Github中的一部分垃圾替代部分需要兩行代碼的部分:\t \t [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(wordRange.location +1,wordRange.length-1)]; \t \t [attString addAttribute:NSLinkAttributeName value:@「http://www.google.com」range:wordRange]; – Loxx

+0

@Larcerax - 謹慎地闡述爲什麼你的代碼片段是一件藝術品,上面貼出的是sh * t? 不知道你是否明白第三方的真正含義..你的代碼是第三方,如上面發佈的任何人想要使用它! –

0

入住此莢:https://cocoapods.org/pods/twitter-text

TwitterText類有一個方法(NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap

Twitter的創建此吊艙在我看來尋找#,@,網址,以便沒有更好的方法來做到這一點。 :)

0

斯威夫特3版@阿努拉格的回答是:

extension String { 
func getHashtags() -> [String]? { 
    let hashtagDetector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpression.Options.caseInsensitive) 
    let results = hashtagDetector?.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, self.characters.count)).map { $0 } 

    return results?.map({ 
     (self as NSString).substring(with: $0.rangeAt(1)) 
    }) 
} 

}