Tim Tim -4 years ago 98
Swift Question

Programmed Button in swift is not working


So I am currently trying to get this button to work called Play button

let playButton: UIButton = {
let button = UIButton()
let image = UIImage(named: "VideoIcon.png") as UIImage?
button.backgroundImage(for: .normal)
button.addTarget(self, action: #selector(pressBackButton(button:)), for: .touchUpInside)
button.setImage(image, for: .normal)

return button

func pressBackButton(button: UIButton) {
if let playVideoButtonURL = post?.videourl {

let player = AVPlayer(url: playVideoButtonURL as URL)
let playerLayer = AVPlayerLayer(player:player)
playerLayer.frame = CGRect(x: 100, y: 200, width: 100, height: 100)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill



When I click on it nothing happens even if the video code is wrong it should still print test. It's not giving me any errors on startup to work with either. The paste bin has my full code.

Answer Source

I tried your code given in question, with explicitly set frame.

override func viewDidLoad() {

    // Set Frame
    self.playButton.frame = CGRect(origin: CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2), size: CGSize(width: 30, height: 30))

And its working perfectly and the "Test" is printing.

Then I checked your code you posted in given link. There I found this method addConstraintsWithFormat to set autolayout with visual format language. I replaced my code using this method.

self.view.addConstraintsWithFormat(format: "H:|-280-[v0(44)]", view: playButton)
self.view.addConstraintsWithFormat(format: "V:|-90-[v0(44)]", view: playButton)

It is also working.

From your code I can find that it's a CollectionViewCell. Could please try to add subviews to its contentView?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download