我有一个 UICollectionViewCell
(比如 UICollectionViewCell 1
),单元格内有一个按钮和 UITextfields
。连接到 (ViewController 1
) 的 UICollectionViewCell
将 ViewController 1
推送到 detailedCollectionViewCell
,即 ( ViewController 2
),它还在单元格内包含一个按钮和 UITextfields
。
这是通过协议(protocol)和委托(delegate)完成的。我的问题是,我想将位于 UICollectionViewCell
(ViewController 1
) 中的 UITextfields
的数据传递到 detailedViewCell UITextfield
(ViewController 2
) 当点击第一个 UICollectionViewCell
(viewController 1
) 中的按钮时。
这是我的代码:
//Protocol View Controller 1
protocol InfoCellDelegate: class {
func buttonToDetailCell()
}
// Inside ViewController 1 class
func buttonToDetailCell() {
let vc = InfoViewController(collectionViewLayout: UICollectionViewFlowLayout())
navigationController?.pushViewController(vc, animated: true)
}
// UICollectionViewCell
weak var delegate: InfoCellDelegate?
@objc func InfoButtonPressed(_ sender: UIButton) {
if cellOne.text != "" {
delegate?.buttonToDetailCell()
}
}
最佳答案
由于您使用的是自定义委托(delegate)协议(protocol),因此您可以控制可以传递给函数的参数。
protocol InfoCellDelegate: class {
func buttonToDetailCell(text: String?)
}
delegate?.buttonToDetailCell(text: textField.text)
话虽如此,我认为更干净的解决方案是不使用按钮,并直接使用 collectionView(_:, didSelectItemAt:)
捕获 Collection View 选择事件。
然后您可以从单元格中检索值。
// in VC1
collectionView.delegate = self
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? MyCell
let text = cell?.textField.text
// do something with text
}
编辑: 这是一些半完整的伪代码,可以执行类似您所追求的操作。
protocol ButtonDelegate: class {
func buttonTapped(text: String?)
}
class ViewControllerOne: UIViewController, UICollectionViewDataSource, ButtonDelegate {
func buttonTapped(text: String?) {
let vc = ViewControllerTwo(nibName: nil, bundle: nil)
vc.text = text
self.present(vc, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: MyCell = collectionView.dequeueReusableCell... // etc.
cell.delegate = self
return cell
}
}
class ViewControllerTwo: UIViewController {
var text: String?
}
class MyCell: UICollectionViewCell {
var button = UIButton()
var textField = UITextField()
weak var delegate: ButtonDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func buttonTapped(_ sender: UIButton) {
self.delegate?.buttonTapped(text: self.textField.text)
}
}
关于swift - 使用 Swift 将数据从 UICollectionViewCell 传递到代码中的另一个 UICollectionViewCell,无需 Storyboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351238/