我有一个自定义的UIPicker单元格我想把选中的项传递给didSelectRow"到另一个自定义单元格,我尝试用委托这样做,但问题是我不能将委托设置为接收器自定义单元格(到我想接收数据的那个),所以…下面是我的代码:
UIPickerView细胞:
import UIKit
protocol AlbumsPickerCellDelegate {
func didSelectedAlbum(_ selectedAlbum: String)
}
class AlbumsPickerTableViewCell: UITableViewCell {
// var indexPath: IndexPath!
@IBOutlet var albumsPicker: UIPickerView!
var pickerData = ["Album1", "Album2", "Album3"]
var albumsPickerCellDelegate: AlbumsPickerCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.albumsPicker.delegate = self
self.albumsPicker.dataSource = self
}
class func cellHeight() -> CGFloat {
return 162.0
}
}
extension AlbumsPickerTableViewCell: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(pickerData[row])
//TODO: Pass the selected data to the albumCell to update the label:
let selectedAlbumOption = pickerData[row]
print("Selected Item: (selectedAlbumOption)")
if let delegate = albumsPickerCellDelegate {
delegate.didSelectedAlbum(selectedAlbumOption)
}
}
}
另一个自定义单元格(我希望数据传递给它):
import UIKit
class AlbumCell: UITableViewCell, AlbumsPickerCellDelegate {
func didSelectedAlbum(_ selectedAlbum: String) {
DispatchQueue.main.async {
self.chosenAlbumLabel.text = selectedAlbum
}
}
@IBOutlet var albumTitleLabel: UILabel!
@IBOutlet var chosenAlbumLabel: UILabel!
var albumsPickerTableViewCell = AlbumsPickerTableViewCell()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
albumsPickerTableViewCell.albumsPickerCellDelegate = self
}
func configureCell(choosenAlbum: String) {
// albumTitleLabel.text = text
chosenAlbumLabel.text = choosenAlbum
}
}
这不起作用,因为在AlbumCell
中您创建了AlbumsPickerTableViewCell
的另一个实例并使用它进行委托。
一般来说,实现从一个单元到另一个单元的委托感觉不对。当您需要控制器中第一个单元格的值而无法获得它时,您可能很快就会发现自己处于这种情况。此外,如果这些单元格要被表视图重用,可能会发生奇怪的行为。
在您的情况下,值得将包含UITableView
的UIViewController
作为AlbumsPickerTableViewCell
的委托,当它从单元调用时,将数据传递给AlbumCell
。
另外,不要忘记对委托的引用应该是weak
,以防止强引用循环。