iOS lets TextView support Special tab Click Response (@ tag, #标签)

Source: Internet
Author: User
Tags hash regular expression uikit
Sina Weibo has been used to find that Weibo provides several special symbolic labels for the messages sent.
For example: Enter "@+ Weibo user nickname (ie ID) + space or punctuation", then in this micro-blog This @ entry will appear as a hyperlink form, click to jump to the @ of someone's microblog.
Another example is the topic tag "#+ keyword +#". The expression is a hyperlink to the search results page that will jump to the microblog that contains the keyword when clicked.

Similarly, the direct input "http://hangge.com" will be displayed as a clickable link to the Web page in the microblog.

1, let TextView support special symbol label

Typically, these tagged content with special tags are considered plain text for multiline text boxes (Uitextview), and we can use the TextView URL detection function to support clicks.

(1) First traversal of the text content, the various special text replaced by our custom URL scheme. For example: Use Mention://hangge to express @hangge, with hash://Air song to express #航歌 #
(2) through the TextView uitextfielddelegate proxy Shouldinteractwithurl method, we can capture these custom URL scheme clicks and then perform different operations by judging the url.scheme.
2, see the effect chart first
(1) We put two textview on the page, and the following one is used to edit the text.

(2) Click the "Send" button will be the content in the above a textview display, you can see the special symbol of the fields are displayed as clickable state.

(3) Test the Click Response event of each label.
3, to achieve the steps
(1) for TextView to be displayed, tick its detection links (link detection) and remove the Editable (so that it is not editable).

2) Extended UITextView:UITextFieldExtension.swift

Import Uikit

Extension Uitextview {

/**
Convert Special symbol Label field
*/
Func resolvehashtags () {
Let nstext:nsstring = Self.text
Font style with default settings
Let attrs = [nsfontattributename:self.font!]
Let attrstring = Nsmutableattributedstring (String:nstext As String,
ATTRIBUTES:ATTRS)

Used to record the index position of the traversal string
var bookmark = 0
Special symbol for split
Let Charactersset = Nscharacterset (charactersinstring: "@#")

Split the string by space and separator first
Let sentences:[nsstring] = Self.text.componentsSeparatedByCharactersInSet (
Nscharacterset.whitespaceandnewlinecharacterset ())

For sentence in sentences {
If the URL link is skipped
If!verifyurl (sentence as String) {
and divide by special symbol
Let words:[nsstring] = Sentence.componentsseparatedbycharactersinset (
Charactersset)
var bookmark2 = Bookmark
For I in 0..<words.count{
Let Word = words[i]
let keyword = chopoffnonalphanumericcharacters (Word as String)
If keyword!= "" && i>0{
Use custom scheme to represent a variety of special links, such as: Mention:hangge
Make these fields blue and clickable

Range of Matches
Let remainingrangelength = min ((nstext.length-bookmark2 + 1),
WORD.LENGTH+2)
Let Remainingrange = Nsrange (location:bookmark2-1,
Length:remainingrangelength)
Print (keyword, bookmark2, remainingrangelength)

Match @ Someone
var matchrange = nstext.rangeofstring ("@\ (keyword)",
Options:. Literalsearch,
Range:remainingrange)
Attrstring.addattribute (Nslinkattributename,
Value: "mention:\ (keyword)",
Range:matchrange)

Match # Topic #
Matchrange = Nstext.rangeofstring ("#\ (keyword) #",
Options:. Literalsearch,
Range:remainingrange)
Attrstring.addattribute (Nslinkattributename,
Value: "hash:\ (keyword)",
Range:matchrange)
}
Moving a coordinate index record
Bookmark2 + = word.length + 1
}
}

Moving a coordinate index record
Bookmark + + 1 sentence.length
}

Print (Nstext.length,bookmark)

Final Assignment
Self.attributedtext = attrstring
}

/**
Verify URL format is correct
*/
Private func Verifyurl (str:string)-> Bool {
Create a regular Expression object
do {
Let Datadetector = Try Nsdatadetector (types:
Nstextcheckingtypes (NSTextCheckingType.Link.rawValue))
Match string, return result set
Let res = datadetector.matchesinstring (str,
Options:nsmatchingoptions (rawvalue:0),
Range:nsmakerange (0, Str.characters.count))
Judgment result (exact match)
if Res.count = = 1 && res[0].range.location = 0
&& Res[0].range.length = = Str.characters.count {
return True
}
}
catch {
Print (Error)
}
return False
}

/**
Extra non-numeric and character parts of the filter department
For example: @hangge. 123-> @hangge
*/
Func chopoffnonalphanumericcharacters (text:string)-> String {
Let nonalphanumericcharacters = Nscharacterset
. Alphanumericcharacterset (). Invertedset
Let Characterarray = text
. Componentsseparatedbycharactersinset (Nonalphanumericcharacters)
return characterarray[0]
}
}

(3) test the page code:


Import Uikit

Class Viewcontroller:uiviewcontroller, Uitextviewdelegate {

Show text Box
@IBOutlet weak var displaytextview:uitextview!
Edit text Box
@IBOutlet weak var edittextview:uitextview!

Override Func Viewdidload () {
Super.viewdidload ()

Set the proxy for the display text box
Displaytextview.delegate = Self
}

Send a message
@IBAction func setmessage (sender:anyobject) {
Set the contents of a Display text box
Displaytextview.text = Edittextview.text
Deal with special label fields in the content
Displaytextview.resolvehashtags ()
Empty the contents of the input box
Edittextview.text = ""
}

Show text Box Link Click response
Func TextView (Textview:uitextview, Shouldinteractwithurl Url:nsurl,
InRange characterrange:nsrange)-> Bool {
To determine URL scheme
Switch Url.scheme {
Case "Hash":
Showalert ("Hash", Payload:
url.resourcespecifier.stringbyremovingpercentencoding!)
Case "mention":
Showalert ("Mention", Payload:
url.resourcespecifier.stringbyremovingpercentencoding!)
Default
Print ("This is a generic URL link")
}

return True
}

Display message
Func Showalert (tagtype:string, payload:string) {
Let Alertcontroller = Uialertcontroller (title: "Detected \ (tagtype) label",
Message:payload, Preferredstyle:. Alert)
Let cancelaction = uialertaction (title: "OK", style:. Cancel, Handler:nil)
Alertcontroller.addaction (cancelaction)
Self.presentviewcontroller (Alertcontroller, Animated:true, Completion:nil)
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

Original: www.hangge.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.