在文本视图中打开链接
Open links in textview
我正在为一个项目编写代码,用户按下一个按钮,然后在按钮下方的文本视图(名为 textoutput)中按下一个按钮,程序随机从我命名为 textinfo 的数组中获取一个 link。当 运行 项目第一次按下按钮并按下 link 时,右侧 link 在 safari 中打开,但第二次按下按钮并随机选择一个新的 link 显示,当按下 link 时,它打开第一个 link 而不是按下的那个。每次按下只有第一个 link 打开的按钮时,每次按下新的 link。
@IBAction func Frukostaction(sender: UIButton) {
let random = Int(arc4random_uniform(19))
textoutput.text = textinfo[random]
}
如何解决这个问题?提前致谢。
我通过设置 UITextView.delegate
然后在 shouldInteractWithURL
函数中手动调用 openURL 解决了这个问题。例如。
let links = ["http://www.google.com","http://www.yahoo.com","http://www.discovery.com"]
var textView : UITextView!
var currentLinkIndex : Int = 0
@IBAction func buttonClick(sender: AnyObject) {
let random : Int = Int(arc4random()) % 3
textView.text = links[random]
currentLinkIndex = random
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
let url = NSURL(string:links[currentLinkIndex])
UIApplication.sharedApplication().openURL(url!)
return false
}
我正在为一个项目编写代码,用户按下一个按钮,然后在按钮下方的文本视图(名为 textoutput)中按下一个按钮,程序随机从我命名为 textinfo 的数组中获取一个 link。当 运行 项目第一次按下按钮并按下 link 时,右侧 link 在 safari 中打开,但第二次按下按钮并随机选择一个新的 link 显示,当按下 link 时,它打开第一个 link 而不是按下的那个。每次按下只有第一个 link 打开的按钮时,每次按下新的 link。
@IBAction func Frukostaction(sender: UIButton) {
let random = Int(arc4random_uniform(19))
textoutput.text = textinfo[random]
}
如何解决这个问题?提前致谢。
我通过设置 UITextView.delegate
然后在 shouldInteractWithURL
函数中手动调用 openURL 解决了这个问题。例如。
let links = ["http://www.google.com","http://www.yahoo.com","http://www.discovery.com"]
var textView : UITextView!
var currentLinkIndex : Int = 0
@IBAction func buttonClick(sender: AnyObject) {
let random : Int = Int(arc4random()) % 3
textView.text = links[random]
currentLinkIndex = random
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
let url = NSURL(string:links[currentLinkIndex])
UIApplication.sharedApplication().openURL(url!)
return false
}