ios - 从 CollectionViewCell 中的 UIButton 打开 URL

标签 ios swift uicollectionview

我的 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/

相关文章:

ios - 在 iOS (Swift) 的标签栏中隐藏标签

ios - ReactiveCocoa - 忽略所有值

ios - 如何实现自定义 AWSCredentialsProvider

iphone - UIScrollView contentSize 被重置

swift - 更改背景颜色状态栏 iOS

ios - 我试图在退出应用程序时暂停 Sprite Kit 游戏

ios - CollectionView 在键盘出现时向上移动,然后返回到之前的位置

ios - 在核心数据关系中添加子对象 - Swift4

ios - 只向右滚动的 UICollectionView(没有向左、向上或向下滚动)

ios - 无法引用类中的下拉菜单值