代理實現:
protocol FallingObjectDatasourceDelegate:class{ func didCollisionWithTheBallBundary(sender:FallingObjectDatasource , numberOfDisappearedBalls:Int) func didCollisionWithTheBottomBundary(sender:FallingObjectDatasource) } class FallingObjectDatasource: NSObject{ //申明delegate public weak var delegate:FallingObjectDatasourceDelegate? func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?){ if(identifier != nil) , identifier as! String == PathNames.ballBundaryName{ //調用代理方法 self.delegate?.didCollisionWithTheBallBundary(sender: self, numberOfDisappearedBalls: self.totalDrops - self.drops.count) }else if identifier as? String == PathNames.referenceBundayName{ //調用代理方法 self.delegate?.didCollisionWithTheBottomBundary(sender: self) } } }
接下來就在要使用代理的類中實現其方法即可。
單例:
private let shareInstance = GameEngine() class GameEngine: NSObject,FallingObjectDatasourceDelegate { class var share: GameEngine { return shareInstance } }
使用: GameEngine.share.方法名。