在我的应用程序中,我有一个UIButton (化身按钮,显示一个profileVC)在UICollectionView中,这个按钮显示在大约4到5个其他视图中。目前,我正在每个视图控制器中添加cellForItemAtIndexPath中的目标,并从公共函数pushNewViews中推送视图。我在想他们是不是更好的方法?(减去重复)
class ShotsViewController: UIViewController{
//CollectionView
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell2", forIndexPath: indexPath) as! mainCell
cell.userImg.addTarget(self, action: #selector(ShotsViewController.showProfileView(_:)), forControlEvents: .TouchUpInside)
}
//Target Func
func showProfileView(sender: AnimatableButton) {
let profileUser = shots[sender.tag].user
pushNewViews.showProfileViewController(profileUser, navigation: navigationController!, storyboard: storyboard!)
} }
class pushNewViews{
class func showProfileViewController(user: User, navigation: UINavigationController, storyboard: UIStoryboard){
let vc = storyboard.instantiateViewControllerWithIdentifier("profileView") as! ProfileViewController
vc.user = user
navigation.pushViewController(vc, animated: true)
}
}发布于 2016-03-25 17:34:40
这里有几个选项,具体取决于您希望将此视图与"push“操作进行耦合的显式程度。
我喜欢的一种选择是依赖现有的应答链。这使您可以灵活地允许视图从视图层次结构中的任何位置发出事件,并在父视图、视图控制器或应用程序委托中处理这些事件。我喜欢这样,它避免了将单元格连接到查看控制器的开销(无论是通过目标操作模式来查看控制器,还是通过委托协议),但是通过权衡,哪个类将响应一个事件并需要更多的集成测试就变得不那么明显了。
// Traverse the responder chain looking for the first responder who conforms to a provided generic type
extension UIResponder {
func handoffEvent<T>(@noescape eventHandler: (T) -> Void) {
var nextResponder: UIResponder?
nextResponder = self
while((nextResponder) != nil) {
if let responder = nextResponder as? T {
eventHandler(responder)
return
}
nextResponder = nextResponder?.nextResponder()
}
// FIXME: you probably want some warning if you fail to find a responder of the expected type
}
}
// Define a protocol for our responder
protocol ControllerRouter {
func pushUserProfileViewController(user: User)
}
// Views can then send events up the responder chain to be handled by some responder who adopts our protocol but the view doesn't need to know anything about who that responder is
class SomeCustomView: UIView {
@IBAction func didPressProfileButton() {
self.handoffEvent { (handler: ControllerRouter) in
handler.pushCurrentUserProfileViewController(self.user)
}
}
}
// Some class in the responder chain needs to implement our protocol to handle the event
class ViewControllerOrAppDelegateOrWhatever: ControllerRouter {
func pushCurrentUserProfileViewController(user: User) {
guard
let navigationController = self.navigationController,
let profileViewController = self.storyboard.instantiateViewControllerWithIdentifier("profileView") as? ProfileViewController
else {
// FIXME: do not ignore unexpected nils
return
}
profileViewController.user = user
navigationController.pushViewController(profileViewController, animated: true)
}
}https://codereview.stackexchange.com/questions/123781
复制相似问题