我的 UICollectionViewCell
中有一个 UIButton
,它从 JSON 获取数据。现在我需要从每个按钮打开一个 URL(每个按钮都有一个不同的 url,它也来自 JSON)。
我成功打开了 URL:
let weburl = "http://example.com"
UIApplication.shared.openURL(URL(string: weburl)!)
但现在我需要向每个按钮传递一个 url。关于如何实现这一目标的任何想法?
最佳答案
你可以有一个 url 数组:
let urls = [url1, url2, ...]
然后将每个按钮的标签属性赋给其对应url的索引。现在您可以轻松管理您想要的内容:
@IBAction func handleTouch(_ sender: UIButton) {
// assumes that the buttons' tags start at 0, which isn't a good idea.
// see @rmaddy comment bellow
let url = urls[sender.tag]
// use the version of the open method shown bellow because the other one becomes deprecated in iOS 10
UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
}
编辑
其他解决方案是仅将 url 存储在单元格本身中,然后在按钮处理程序中打开与其单元格对应的 url。
关于ios - 从 CollectionViewCell 中的 UIButton 打开 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385974/