在自定义TableViewCell中按下按钮时,从API打开URL



我想点击自定义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正确。

由于操作与视图控制器没有直接关系,因此将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
}

旁注:

您的第一个片段是Swift 2代码。Swift 3+中永远不会调用该方法

您需要

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

最新更新