2016-09-30 7 views
0

Swift 3でXcode8に更新されました。残念ながら、ターゲットが別のクラスの関数を参照するボタンにターゲットを追加できません。Swift 3#セレクタとタイプ名

class AddToDoViewController { 
    @IBOutlet weak var doneButton: UIButton! 
    var st : SelectorTest! 

    override func viewDidLoad() { 
     st = SelectorTest() 

     st.didTapButtonHandler = { 
     self.doneButton.isSelected = !self.doneButton.isSelected 
     print("self.doneButton.selected=\(self.doneButton.isSelected)") 
     } 

     doneButton.addTarget(self, action: #selector(SelectorTest.didTapTheButton(_:)), for: .touchUpInside) 
    } 
} 


class SelectorTest { 
    typealias ToDoCellDidTapButtonHandler =() -> Void 
    var didTapButtonHandler: ToDoCellDidTapButtonHandler? 

    @objc func didTapTheButton(_ sender: AnyObject) { 
     if let handler = didTapButtonHandler { 
      handler() 
     } 
    } 
} 

この場合、ターゲットはSelectorTest.destTapButton(_ :)で、SelectorTestクラスに存在します。私が実行して、しかし、私はランタイムエラーを取得]ボタンをクリックしてください:私は間違いなく存在する

SelectorTest.didTapTheButton(_:) 

、なぜ私は、実行時に取得していますを指すように、ボタンの上にターゲットを設定しているので

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[Done.AddToDoViewController didTapTheButton:]: 
unrecognized selector sent to instance 

AddToDoViewControllerでdidTapTheButton(_:)が見つかりませんというエラーが表示されますか?特にAddToDoViewController.didTapTheButton(_:)をターゲットとして指定しなかった場合はどうなりますか?

Done.AddToDoViewController didTapTheButton: 

#selectorは、クラス名を無視し、ターゲットがボタン(AddToDoViewController)にターゲットを追加したクラスであることを前提としていた場合、私は疑問に思って?

ターゲットをSelectorTest.didTapTheButton(_:)に設定するにはどうすればいいですか?コンフィグレーションされたターゲットではなく存在しないAddToDoViewController.didTapTheButton(_:)を実行しようとするランタイムの代わりに実行時にSelectorTest.didTapTheButton(_:)が実行されますか?

答えて

1

SelectorTestクラスのオブジェクトをaddTargetの代わりにselfの代わりに渡します。 addTarget最初のパラメータの目標で

doneButton.addTarget(st, action: #selector(SelectorTest.didTapTheButton(_:)), for: .touchUpInside) 

Any?

The target object is the object whose action method is called. If you specify nil, UIKit searches the responder chain for an object that responds to the specified action message and delivers the message to that object.

+0

感謝のタイプですが、私は自己とSelectorTestが同じクラスに解決されませんので、あなたは、コンパイル時エラーになるだろうと思うだろう。 – user6902806

+0

ウェルカムメイト:) –

+0

addToDoViewControllerの場合:addTarget(self、action:#selector(SelectorTest.didTapTheButton(_:)...)self!= SelectorTest以降にコンパイル時エラー/警告が出ることを願っています。 self、#セレクタのクラスの型を無視します。 – user6902806

関連する問題