简体   繁体   中英

Swift - SwipingController Programmatic - button doesn't work

I created the SwipingController app. The application was supposed to have the functionality of scrolling with gestures and a management bar with 2 buttons and UIPageControl.

For now, these buttons were supposed to print only a text message in the console, but it doesn't.

 let nextButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("NEXT", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
    button.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)

    return button
}()
@objc func handleNextButton() {
    print("Next Botton Pressed")
}

I wanted to add the whole page management bar in a separate file.

When it goes to the main controller, the whole functionality work.

I don't want to paste all the code, so it gives a link to the git

https://github.com/SebaKrk/SwipingControllerProgrammatic.git

Picture from simulator

The Problem is that you set your target right in the setup code of your UIButton

let previousBotton : UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("PREV", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.addTarget(self, action: #selector(handlePreviousButton), for: .touchUpInside)
        return button
    }()

It seems like the self is not initialized at this point. Because this code is run before your init was run.

So you have to set the target of the Button after you called super.init then it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM