티스토리 뷰

stackoverflow.com/questions/51158390/custom-uibutton-class-for-button-touch-event

 

Custom UIButton class for button touch event

Is it possible to create a custom UIButton class with an touch event animation which gets automatically invoked everytime the user touches the button? import UIKit class AnimatedButton: UIButto...

stackoverflow.com

 

 

 

나에게는 모두 똑같은 액션을 하는 IBAction 함수와 그에 달린 버튼이 있었다. 

이 IBAction 메소드를 모든 ViewController에 달아주려니 너무 많다는 생각이 들어서!.!

아예 override해서 사용하는 방법은 없나? 찾아보게 되었다. 

 

 

class CustomButton:UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        configeBtn()
    }

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
        configeBtn()
    }

    func configeBtn() {

        self.addTarget(self, action: #selector(btnClicked(_:)), for: .touchUpInside)

    }

    @objc func btnClicked (_ sender:UIButton) {

        // animate here 

    }
}

 

그런데 이렇게 처리하면, self.present 메소드를 쓸 수 없다는 문제가 생겼다. 나는 결국 사이드바 버튼을 눌러서 새로운 vc를 내 위에 띄워주려는 거라서 self에 대한 참조는 꼭 필요했다. 

 

그럼 어떻게 하면 좋을까 하다가 stackoverflow.com/questions/43998608/custom-uibutton-class-with-same-action-for-different-viewcontrollers 이 글을 보게 되었다. 여기서는 default vc를 만들어서, 사이드바 버튼이 필요한 모든 vc에 대해서 이 default vc를 상속받는 방식으로 하라고 했다. 

 

 

 

바꿔준 모습. @IBAction에 약 30개정도의 버튼을 드래그해서 달아줬다 ㅠ 귀찮..

 

코드는 훨씬 간결해지긴 했는데, 바꾸는 일 자체는 매우 귀찮았다.  첨부터 이런식으로 할걸 ㅠ 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함