我有ViewController,里面有UIView。
这个UIView有单独的myView类,有很多UI元素 - 其中一个是CollectionView。
我想要的是在选择myView中的一个集合元素时执行segue。但是当我尝试添加行
时performSegue(withIdentifier: "myIdintifier", sender: self)
收集视图 didSelectItemAt 方法我收到错误
使用未解析的标识符' performSegue'
我明白这是因为我在扩展UIView而不是UIViewController的类中执行此操作。
那么在这种情况下如何才能完成segue?还有我如何准备segue?
答案 0 :(得分:1)
您可以使用协议/代表来实现。
TotalPrice.text = String((total1 ?? 0) + (total2 ?? 0))
答案 1 :(得分:1)
在这里,我将逐步评估它。
步骤1
使用协议创建自定义委托,如下所示代码段将引导您进行自定义UIView。 protocol
必须存在于您的自定义视图范围之外。
protocol CellTapped: class {
/// Method
func cellGotTapped(indexOfCell: Int)
}
不要忘记在自定义视图
上创建以下类的委托变量var delegate: CellTapped!
使用您的集合视图didSelect方法,如下所示
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if(delegate != nil) {
self.delegate.cellGotTapped(indexOfCell: indexPath.item)
}
}
步骤2
让我们来看你的视图控制器。将CellTapped
提供给您的viewcontroller。
class ViewController: UIViewController,CellTapped {
@IBOutlet weak var myView: MyUIView! //Here is your custom view outlet
override func viewDidLoad() {
super.viewDidLoad()
myView.delegate = self //Assign delegate to self
}
// Here you will get the event while you tapped the cell. inside it you can perform your performSegue method.
func cellGotTapped(indexOfCell: Int) {
print("Tapped cell is \(indexOfCell)")
}
}
希望这会对你有所帮助。
答案 2 :(得分:0)
除了定义协议,您还可以使用Notification。 首先,范围nonfiction.name:
extension Notification.Name {
static let yourNotificationName = Notification.Name(“yourNotificationName”)
}
然后在您要执行segue但不能在自定义UIView中执行的位置:
NotificationCenter.default.post(name: .yourNotificationName, object: self)
最后,您可以在viewControllers中收听通知:
private var observer: NSObjectProtocol?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: .yourNotificationName, object: nil, queue: nil) {notification in
self.performSegue(withIdentifier:”your segue”, sender: notification.object}
别忘了删除它:
override func viewWillDisappear(_ animated: Bool){
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}