2016-11-19 88 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