我有一个自定义tableView,它有2个标签和一个按钮。 我想要做的是当我按下特定单元格中的按钮时,打印该单元格中标签的文本。
我使用了委托让按钮像这样工作。
**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!
答案 0 :(得分:5)
这里显示数据的问题是什么。您将索引值作为didPressButton
委托中的标记作为参数发送。当您在此处获得委托中的索引值时,您只需显示其中的值。
假设您从cellForRowAtIndexPath
中的数组传递值,您只需要按如下方式打印它。
func didPressButton(_ tag: Int) {
print("I have pressed a button")
let contacts = self.contacts[tag]
print(contacts.givenName)
}
另外,不要忘记在YourCellDelegate
的接口声明中设置UIViewController
,如class myViewController: UIViewController,YourCellDelegate {
答案 1 :(得分:1)
func didPressButton(_ tag: Int) {
let selectedContact = self.contacts[tag]
// Now use `selectedContact` to fetch Name and Phone Number
}