2017-08-09 14 views
0

私はテキストフィールドを持っており、テキストをクリックできるようにしたいと考えています。以下は私のコードです。Swiftのハイパーリンクテキストを使用したUITextView

let string = "Google" 
let linkString = NSMutableAttributedString(string: string) 
linkString.addAttribute(NSLinkAttributeName, value: NSURL(string: "https://www.google.com")!, range: NSMakeRange(0, string.characters.count)) 
linkString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 25.0)!, range: NSMakeRange(0, string.characters.count)) 
textView.attributedText = linkString 
textView.selectable = true 
textView.userInteractionEnabled = true 
+0

例えば使用のTextViewをURLを開くことができます –

答えて

1

あなたUITextViewリンク、にphoneNumber、住所、calendarEventを検出するか、単に使用UIDataDetectorTypesよりも、すべてのタイプを検出したい場合。

let yourstring = "Check Google search. www.google.com" 

// Update UITextView font and font size. 
textVw.font = UIFont(name: "HelveticaNeue", size: 25) 

// Make web links clickable 
textVw.isUserInteractionEnabled = true 
textVw.isSelectable = true 
textVw.isEditable = false 
textVw.dataDetectorTypes = UIDataDetectorTypes.link 

// Update UITextView content 
textVw.text = yourstring 

// Update hyperlink text colour. 
textVw.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.blue, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleNone.rawValue] 

textVwあなたはまた、ストーリーボードからのスクリーンショット以下のようにテキストを検出可能にすることができUITextView

@IBOutlet var textVw: UITextView! 

としての目的です。 Attribute inspector

0

あなたがUITextFieldクリック可能にするために、このコードを使用してテキストフィールドの代わりに、あなたのコンセプトのため

// This is the label 
    @IBOutlet weak var label: UILabel! 

override func loadView() { 
    super.loadView() 

    // here is where you make your label clickable 
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.onClicLabel(sender:))) 
    label.isUserInteractionEnabled = true 
    label.addGestureRecognizer(tap) 
} 

// And here are the functions to open a URL 
func onClicLabel(sender:UITapGestureRecognizer) { 
    openUrl(urlString: "http://www.google.com") 
} 


func openUrl(urlString:String!) { 
    let url = URL(string: urlString)! 
    if #available(iOS 10.0, *) { 
     UIApplication.shared.open(url, options: [:], completionHandler: nil) 
    } else { 
     UIApplication.shared.openURL(url) 
    } 
} 
関連する問題