2016-12-15 98 views
0

我在xcode 3的视图表控制器中使用了一个按钮,我希望右侧的所有getbutton打开不同的链接,我该怎么做。如何将不同的链接添加到一组按钮?

enter image description here

我不知道如何做到这一点。我试图添加一个数组并访问它们,但它不起作用。

+0

这是一个自定义的UITableViewCell类?你有没有考虑过为你的单元类创建一个协议并使视图控制器符合该协议?所以,当你点击按钮时,你将单元本身传递给协议方法,以便在实现中获得它的索引,并为你提到的数组获得正确的索引。 – Prientus

+0

我该怎么做? – BallisticDiamond

+0

我会给你发一张我的代码图片,这样你就可以看到我有什么 – BallisticDiamond

回答

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) 
} 
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) 
     } 
    } 
} 
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) 
}