【问题标题】:Open URL from API when Button is Pressed in Custom TableViewCell在自定义 TableViewCell 中按下按钮时从 API 打开 URL
【发布时间】:2020-03-08 16:58:38
【问题描述】:

我想单击自定义 xib 文件中的按钮,然后它会转到使用可解码的 api 传递的链接。

我可以使用以下方法将整行重定向到来自 api 的链接:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let item = page!.tradeshows[indexPath.row]

    if let eventURLS = item.url {

    UIApplication.sharedApplication().openURL(eventURLS, options: [:], completionHandler: nil)
    } else {print("link not working")
  }
}

但我不想选择整行,我只想从自定义 .xib 文件中选择按钮。

我也试过了:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) - > UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell",
        for: indexPath) as!EventTableViewCell
    let item = page!.tradeshows[indexPath.row]

    cell.registerButton.addTarget(self, action: #selector(UpcomingEventsViewController.onClickedRegistrationButton(_: )),
        for: .touchUpInside)

    cell.registerButton.tag = indexPath.row

    return cell
}

@objc func onClickedRegistrationButton(_ button: UIButton) {
    let buttonLink = button.tag
}

但我不确定如何设置来自 json 数据的链接,以便使用第二种方法使 indexPath 正确。

【问题讨论】:

  • 属性名以小写字母tableData开始
  • 最好将你的项目更新到最新的 swift ,swift 2 现在不能上传到商店
  • 还有2个数组page!.tradeshowstableData 决定哪1个是onClickedRegistrationButton内正确访问的表数据源
  • 我更新了第一个代码 sn-p 所以它是我实际项目中的一个例子。在它只是相似之前。

标签: ios json swift api uitableview


【解决方案1】:

由于操作与视图控制器没有直接关系,因此将 URL 传递给单元格并在那里打开 URL 会更有效。不需要目标/操作代码。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as! EventTableViewCell
    let item = page!.tradeshows[indexPath.row]
    cell.url = item.url
    return cell
}

在单元格中为按钮添加属性urlIBAction

class EventTableViewCell : UITableViewCell {

    var url : URL!

    // other properties

    @IBAction func pushButton(_ sender : UIButton) {
       UIApplication.shared.open(url) 
    }

    // other code
}

旁注:

您的第一个 sn-p 是 Swift 2 代码。该方法永远不会在 Swift 3+ 中被调用

【讨论】:

    【解决方案2】:

    你需要

    @objc func onClickedRegistrationButton(_ button: UIButton) {  
        UIApplication.sharedApplication().openURL(NSURL(string:tableData[button.tag])!) 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多