Skip to content

Instantly share code, notes, and snippets.

@Arime9
Last active January 24, 2019 06:27
Show Gist options
  • Save Arime9/645510fb238c7fdde99d072f1094572a to your computer and use it in GitHub Desktop.
Save Arime9/645510fb238c7fdde99d072f1094572a to your computer and use it in GitHub Desktop.
【Swift+Extension】UITextViewで、ハイパーリンクに対応する ref: https://qiita.com/Arime/items/d9f679b13921a8bfe515
let textView = UITextView()
textView.text = "Googleのリンク"
textView.addLink(pattern: "Google", urlString: "https://www.google.com", color: .blue)
class LinkSampleViewController: UIViewController, UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return true
}
}
let textView = UITextView()
textView.text = "Googleのリンク"
let linkRepresents = textView.addLink(pattern: "Google", urlString: "https://www.google.com", color: .blue) { (textView, url, characterRange, interaction) -> Bool in
return true
}
import UIKit
final class LinkTextViewDelegateRepresents: NSObject {
typealias Action = (_ textView: UITextView, _ url: URL, _ characterRange: NSRange, _ interaction: UITextItemInteraction) -> Bool
var action: Action
init(action: @escaping Action) {
self.action = action
}
}
extension LinkTextViewDelegateRepresents: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
return action(textView, URL, characterRange, interaction)
}
}
import Foundation
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
func ranges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [Range<String.Index>] {
var ranges: [Range<String.Index>] = []
while let range = range(of: searchString, options: mask, range: (ranges.last?.upperBound ?? startIndex)..<endIndex, locale: locale) {
ranges.append(range)
}
return ranges
}
func nsRanges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [NSRange] {
let ranges = self.ranges(of: searchString, options: mask, locale: locale)
return ranges.map { nsRange(from: $0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment