UIButton in Swift is not registering touches

后端 未结 18 916
情深已故
情深已故 2020-12-29 21:11

I\'m trying to create a UIButton using Swift. It compiles fine and I can see my button in the simulator, but when I click it, nothing happens. This is the code I am using:

18条回答
  •  渐次进展
    2020-12-29 21:30

    I've found similar example for Swift 2 and adapted for Swift 3. Tested it is working very well. I hope it helps.

    // http://lab.dejaworks.com/ios-swift-3-playground-uibutton-action
    // Trevor D. Beydag
    
    import UIKit
    import PlaygroundSupport
    class Responder : NSObject {
        func action() {
            print("Button pressed!")
        }
    }
    
    let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 300.0,    height: 600.0))
    PlaygroundPage.current.liveView = containerView
    let responder = Responder()
    
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    button.backgroundColor = UIColor.green
    button.setTitle("TEST", for: .normal)
    button.addTarget(responder, action: #selector(Responder.action), for: .touchUpInside)
    containerView.addSubview(button)
    

提交回复
热议问题