Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift3: Add button with code

Tags:

ios

swift3

swift2

Im reading Apples swift (iOS) documentation but its written for Swift 2 and i use Swift 3. I want to add a button programmatically but its seems there is a change and I can't find how to fix it.

Here is the Code for the Swift 2 example:

import UIKit

class RatingControl: UIView {

// MARK: Initialization

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

    // Buttons
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    button.backgroundColor = UIColor.red()
    button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
    addSubview(button)
}

override func intrinsicContentSize() -> CGSize {
    return CGSize(width: 240, height: 44)
}

// MARK: Button Action

func ratingButtonTapped(button: UIButton){
    print("Button pressed")
}
}

The only change i made after the 'fix-it' showed the error is this in the selector:

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown)

This should have printed "Button pressed" but it doesn't. Any help?

like image 958
pRivaT3 BuG Avatar asked Jul 16 '16 22:07

pRivaT3 BuG


2 Answers

My code:

button.backgroundColor = UIColor.red

button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)

override var intrinsicContentSize : CGSize {
//override func intrinsicContentSize() -> CGSize {
    //...
    return CGSize(width: 240, height: 44)
}

// MARK: Button Action
func ratingButtonTapped(_ button: UIButton) {
    print("Button pressed 👍")
}
like image 75
Vũ Đình Thuần Avatar answered Oct 25 '22 20:10

Vũ Đình Thuần


Try something like this. I haven't tested but it should work:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)
addSubview(button)

func ratingButtonTapped() {
    print("Button pressed")
}
like image 43
axel Avatar answered Oct 25 '22 20:10

axel