【发布时间】:2017-09-11 22:55:04
【问题描述】:
我有一个应用程序,它使用了一个包含原型单元格的 tableView。这个原型单元包含一些标签和一个按钮(连接到该单元的 UITableViewCell 文件)。如果不清楚,这就是我的意思:
class ContactsCell: UITableViewCell { //this custom cell is used as the prototype cell for the tableView
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var indexPathRowLabel: UILabel!
@IBOutlet weak var replaceContactButtonUI: UIButton!
@IBAction func replaceContactButtonTapped(_ sender: Any) {
//THIS is the button in question
}
这样做的原因是因为我希望 tableView 中的每个单元格都具有所有这些标签(和按钮),但每一行在标签中具有不同的值。这些值由cellForRowAt tableView 函数通过如下系统处理:
按下一个按钮(不是我所说的单元格中的按钮......在 VC 顶部,tableView 之外的另一个按钮)会打开联系人选择器:
func selectContact(){//allows user to bring up contactPicker
let contactPicker = CNContactPickerViewController()
contactPicker.displayedPropertyKeys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey]
contactPicker.delegate = self
contactPicker.predicateForEnablingContact = NSPredicate(format: "phoneNumbers.@count >= 0")
contactPicker.predicateForSelectionOfContact = NSPredicate(format: "phoneNumbers.@count >= 1")
self.present(contactPicker, animated: true, completion: nil)
}
@IBAction func selectContactsButton(_ sender: Any) {
selectContact()
//button brings up the picker to allow selection of contact
}
选择其中一个联系人会更新一个数组,tableView 使用该数组来更新标签的值:
func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
contactArray.append(contactProperty.contact)
print(contactArray)// contactArray = [CNContact]()
contactsTableView.reloadData()// reloads the value of the labels
dismiss(animated: true)
}
这些都按预期工作。但是,我在每个单元格中的 in 按钮遇到了一些问题。此按钮旨在允许替换 tableView 中按下按钮的行中的CNContact...(即,如果有 4 行,则有 4 个“替换”按钮。单击“替换”第三行的按钮替换了contactArray 的第二个索引处的CNContact)。不过,这就是我的问题所在。由于按钮及其操作位于 UITableViewCell 的 swift 文件中,而 not 位于 tableViewControllers 中,因此它无法访问 contactArray 来删除和附加,也无法访问选取器功能以允许新联系人的选择,也不是 tableView 本身运行.reloadData()。我如何“授予访问权限”到 UITableViewCell 的 swift 文件,以利用它所属/连接到的 tableView 控制器中的东西?
注意这个问题的整个前提可能是错了,我应该把按钮的动作放在别处(不是在 UITableViewCell 的 swift 文件中)。如果是这种情况,我应该放在哪里?
【问题讨论】:
标签: swift uitableview