2015-09-25 112 views
-1

斯威夫特代表團你好,我有2類:沒有故事板

第一類是從的UIViewController繼承發件人:

class Sender: UIViewController { 

// ReceiverDelegate property for communicating with viewmodel // 
var delegate: ReceiverDelegate? 

// loginButtonClicked - IBAction called after login button clicked // 
@IBAction func loginButtonClicked(sender: AnyObject) { 
    delegate?.didPressLoginWithCredentials("xx", password: "ss") 

} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    Receiver(vc: self) 
    // Do any additional setup after loading the view, typically from a nib. 
} 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

}

二等就像一個模型和接收器類的不是UIViewController:

protocol ReceiverDelegate { 
func didPressLoginWithCredentials(username: String, password: String) 
} 


class Receiver: ReceiverDelegate { 
init(vc: Sender) { 
    vc.delegate = self 
} 

func didPressLoginWithCredentials(username: String, password: String) { 
    println("THE MESSAGE") 
} 

} 

我想問一下,如果這是一個很好的appr分配委託的過程。我需要在發件人內部以某種方式完成它,因爲Receiver永遠不會被初始化?

我在發送者的viewDidLoad中分配了我的委託。

如果有更好的方法請幫忙! (也許我應該這樣做VAR接收器=接收器(),然後只需調用接收方法,而不代表團?)

回答

1

應該更多這樣的:

class Sender: UIViewController, ReceiverDelegate { 

var receiver: Receiver() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    receiver.delegate = self 
} 

func didPressLoginWithCredentials(username: String, password: String) { 
    println("THE MESSAGE") 
} 

然後在您的接收器:

protocol ReceiverDelegate { 
    func didPressLoginWithCredentials(username: String, password: String) 
} 

class Receiver: NSObject { //or whatever you're subclassing 

    weak var delegate: ReceiverDelegate? 

    init(vc: Sender) { 
     // your initialization code 
    } 

    // loginButtonClicked - IBAction called after login button clicked 
    @IBAction func loginButtonClicked(sender: AnyObject) { 
     delegate?.didPressLoginWithCredentials("xx", password: "ss") 
    } 
} 

它值得注意的是你的代碼有點令人困惑 - 我不知道你的Receiver應該是什麼,但我重新安排了你的代碼,以正確使用協議/委派。 Receiver將需要該登錄按鈕,所以它可能是UIView的一個子類。很難說沒有看到更多。

上面的代碼是如果您有一個帶有按鈕的子視圖,並且您希望視圖控制器處理該操作,您將執行的操作。