2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ios]CustomButtonを生成して、ViewControllerのメソッドを呼び出そうとしたら・・・

Posted at

下記のようなCustomButtonを生成し、ViewControllerのメソッドをButtonに設定しようとしたところ、「unrecognized selector sent to instance」のエラー

CustomButton.swift
class startButton: UIButton {
    
    init(frame: CGRect,title: String) {
        super.init(frame: frame)
        self.setTitle(title, for: .normal)
        self.backgroundColor = UIColor.blue
        self.titleLabel?.font = UIFont.systemFont(ofSize: 26)
        self.layer.cornerRadius = 10
        self.layer.frame = frame
        self.addTarget(ViewController.self, action: #selector(ViewController.self.animateLabel), for: .touchUpInside)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
CustomButton.swift
class ViewController: UIViewController{

    
    override func viewDidLoad() {
        super.viewDidLoad()
      
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    
    @objc func animateLabel(){   
        ・・・中略
}

なんでだろうと色々調べたが、答えがわからず・・・・
ネットの海をさまよっていたところ、delegateに関する記事を発見。
「あれ、これもしかしてデリゲート使わないといけないんじゃね?」と思い、記事を参考に下記ように実装。
無事、動きました。「delegateってtableView使うときに使うもの」とした認識してなかったので、自分の勉強不足を痛感。もっと体系的に勉強したいと思うようになってきました。

CustomButton.swift
@objc protocol startButtonDelegate{
    func animateLabel()
}

class startButton: UIButton {
    weak var delegate: startButtonDelegate?
    
    init(frame: CGRect,title: String) {
        super.init(frame: frame)
        self.setTitle(title, for: .normal)
        self.backgroundColor = UIColor.blue
        self.titleLabel?.font = UIFont.systemFont(ofSize: 26)
        self.layer.cornerRadius = 10
        self.layer.frame = frame
        self.addTarget(self, action: #selector(self.tappedButton), for: .touchUpInside)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tappedButton(){
        self.delegate?.animateLabel()
    }
}

CustomButton.swift
class ViewController: UIViewController,startButtonDelegate{

    
    override func viewDidLoad() {
        super.viewDidLoad()
      
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    
    @objc func animateLabel(){   
        ・・・中略
}

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?