2016-11-19 90 views
0

我有一个TableView通过标签在其中包含数据。当您点击标签点击注册,但现在我想获得点击标签的数据,我很难完成这一工作。我有相同的功能为按钮工作,例如我这样做我的按钮在TableView内。上述iOS swift如何在标签抽头中获取TableView中的标签文本

按钮单击事件

 var locations = [String]() 
     @IBOutlet weak var Location: UIButton! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     TableSource.dataSource = self 


    } 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Registration_Search", for: indexPath) 

     cell.Location.setTitle(locations[indexPath.row], for: UIControlState.normal) 

     cell.Location.addTarget(self, action: #selector(Registration_SearchController.Location_Click(sender:)), for: .touchUpInside) 
     cell.Location.tag = indexPath.row 

     return cell 
    } 

    func Location_Click(sender: UIButton) { 

     print(locations[sender.tag]) 


    } 

该代码可以让我点击任何按钮的数据。我现在尝试为标签执行相同的操作,但无法获取标签所具有的数据。这是我的标签代码哦一样是相同的,但上面的不同视图控制器

 var locations = [String]() 
     @IBOutlet weak var location: UILabel! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     TableSource.dataSource = self 
     location.isUserInteractionEnabled = true 

    } 
      func tapFunctionn(sender: UITapGestureRecognizer) 
{ 
    // I would like to get the data for the tapped label here 
    print("Tapped") 
} 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Registration_Search", for: indexPath) 

      cell.location.text = Locations[indexPath.row] 
      let tap = UITapGestureRecognizer(target:self, action: #selector(HomePageC.tapFunctionn)) 

    cell.location.addGestureRecognizer(tap) 

     return cell 
    } 

当我再次点击打印螺纹,但不能得到实际数据的标签。在按钮功能中,我可以使用Sender.Tag,但UITapGestureRecognizer没有Tag方法。任何建议,将不胜感激

回答

1

您不必使用UITapGestureRecognizer。只需使用委托方法。该UITableView委托设置为您UIViewController,使类符合UITableViewDelegate

为SWIFT 3

override func viewDidLoad() { 
    super.viewDidLoad() 
    TableSource.dataSource = self 
    TableSource.delegate = self 
} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let cell = tableView.cellForRow(at: indexPath) 

    //access the label inside the cell 
    print(cell.label?.text) 
    //or you can access the array object 
    //print(Locations[indexPath.row]) 
} 
+0

这将只是我的工作我试图把它放在一个函数里面,因为事情在下面会变得很复杂。 – user1949387

+0

你可以随时从'didSelect'中调用函数并传递适当的信息。 – Rikh

+0

谢谢,这是需要的 – user1949387

3

你可以让这样的事情:

func tapFunctionn(recognizer: UIPinchGestureRecognizer) { 
    let view = recognizer.view 
    let index = view?.tag 
    print(index) 
} 
+0

这实际上非常接近它,上面的代码的唯一问题是它总是插入第一列的值。我正在使用您的代码,并会尝试使其变为动态 – user1949387