2017-06-12 83 views
0

我有一個自定義的tableView有2個標籤和一個按鈕。 我想要做的是當我按下特定單元格中的按鈕打印該單元格中的標籤中的文本時。如何使用按鈕打印自定義tableview的數據?

我已經使用委託來使按鈕像這樣工作。

**Protocol** 

protocol YourCellDelegate : class { 
    func didPressButton(_ tag: Int) 
} 

**UITableViewCell** 

class YourCell : UITableViewCell 
{ 
    weak var cellDelegate: YourCellDelegate? 

    // connect the button from your cell with this method 
    @IBAction func buttonPressed(_ sender: UIButton) { 
     cellDelegate?.didPressButton(sender.tag) 
    }   
    ... 
} 

**cellForRowAt Function** 

cell.cellDelegate = self 
cell.tag = indexPath.row 

**final Function** 

func didPressButton(_ tag: Int) { 
    print("I have pressed a button") 
} 

現在我該怎樣從特定的單元格中顯示數據

非常感謝您的幫助

編輯

-getting contacts from phone- 

    lazy var contacts: [CNContact] = { 
     let contactStore = CNContactStore() 
     let keysToFetch = [ 
      CNContactFormatter.descriptorForRequiredKeys(for: .fullName), 
      CNContactEmailAddressesKey, 
      CNContactImageDataAvailableKey] as [Any] 

     // Get all the containers 
     var allContainers: [CNContainer] = [] 
     do { 
      allContainers = try contactStore.containers(matching: nil) 
     } catch { 
      print("Error fetching containers") 
     } 

     var results: [CNContact] = [] 

     // Iterate all containers and append their contacts to our results array 
     for container in allContainers { 
      let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) 

      do { 
       let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor]) 
       results.append(contentsOf: containerResults) 
      } catch { 
       print("Error fetching results for container") 
      } 
     } 

     return results 
    }() 

-cellForRowAt- 

let cell = tableView.dequeueReusableCell(withIdentifier: "PersonCell", for: indexPath) as? PersonCell 

     let contacts = self.contacts[indexPath.row] 
     cell?.updateUI(contact: contacts) 

     cell?.cellDelegate = self as? YourCellDelegate 
     cell?.tag = indexPath.row 

     return cell! 

回答

5

什麼在這裏顯示數據的問題。您將didPressButton委託中的索引值作爲標記發送爲參數。當您在這裏獲得代表中的索引值時,您只需顯示其中的值即可。

假設您從cellForRowAtIndexPath中的數組中傳遞值,則只需按如下所示進行打印。

func didPressButton(_ tag: Int) { 
    print("I have pressed a button") 
    let contacts = self.contacts[tag] 
    print(contacts.givenName) 
} 

另外,不要忘記我其實使用名片框架來顯示手機中的聯繫人設置YourCellDelegateUIViewController接口聲明像class myViewController: UIViewController,YourCellDelegate {

+0

。現在我只想打印來自tableView的名稱和電子郵件 –

+0

您能否使用完整的'cellForRowAtIndexPath'函數更新問題。想知道你是如何傳遞數據的。 – Bali

+0

我修改了帖子 –

1
func didPressButton(_ tag: Int) { 
    let selectedContact = self.contacts[tag] 

    // Now use `selectedContact` to fetch Name and Phone Number 
} 
相關問題