答案 0 :(得分:0)
您需要在cellForRow dataSource方法中将按钮的标记设置为indexPath.row。
cell.button.tag = indexPath.row
然后在按钮选择器功能中,您将获得该行的单元格。
func buttonTapped(_ sender: UIButton) {
guard let tappedCell = tableView.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? CustomCellClass, let url = URL(string: tappedCell.modelObject.urlString) else { return }
//assuming the model object you assign to each cell has a link property, you can now access the link for that cell
UIApplication.shared.openURL(url)
}
答案 1 :(得分:0)
这就是我如何做到这一点:
//This is your custom cell class
----------------------------------
protocol CustomCellProtocol {
func didTapGet(cell:UITableViewCell)
}
class CustomCell:UITableViewCell {
var delegate:CustomCellProtocol?
@IBAction func getTapped(id:Any) {
delegate?.didTapGet(cell: self)
}
}
//This is your View controller
-----------------------------------
class YourTableViewController:UIViewController, CustomCellProtocol, UITableViewDataSource {
//Your Code here
var tableView:UITableView?
let urlArray = ["www.example1.com", "www.example2.com"]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! CustomCell
//cell code here
cell.delegate = self
return cell
}
func didTapGet(cell: UITableViewCell) {
if let indexPath = tableView?.indexPath(for: cell), let url = URL(string:urlArray[indexPath.row]) {
UIApplication.shared.open(url, options: [], completionHandler: nil)
}
}
}
答案 2 :(得分:0)
你应该写下这段代码:
var Urlarr = ["http://drivecurrent.com/using-swift-and-avfoundation-to-create-a-custom-camera-view-for-an-ios-app/","https://fabric.io/kits/ios/crashlytics/summary","http://stackoverflow.com/questions/41156065/how-can-i-add-different-links-to-an-array-of-buttons"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Urlarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.TableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
cell.TblButton.tag = indexPath.row
cell.TblButton.addTarget(self,action:#selector(buttonClicked),
for:.touchUpInside)
return cell
}
func buttonClicked(sender:UIButton)
{
UIApplication.shared.openURL(NSURL(string: Urlarr[sender.tag]) as! URL)
}