Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 9 UIButton Initialization

I am trying to initialize a UIButton programmatically but see one of these errors:

buttonWithType is unavailable: use object construction UIButton(type:)

or

error: incorrect argument label in call (have 'buttonWithType:', expected 'type:')

  for char in keys {
        let btn: UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton

        btn.frame = CGRectMake(0, 0, 20, 20)
        btn.setTitle(char, forState: .Normal)
        btn.sizeToFit()
        btn.titleLabel?.font = UIFont.systemFontOfSize(20)

        btn.backgroundColor = UIColor(hue: (216/360.0), saturation: 0.1, brightness: 0.81, alpha: 1)//
        btn.setTitleColor(UIColor(white: 1.0, alpha: 1.0), forState: .Normal)

        btn.setContentHuggingPriority(1000, forAxis: .Horizontal)
        btn.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)

        btn.addTarget(self, action: Selector("handleBtnPress:"), forControlEvents: .TouchUpInside)

        self.addSubview(btn)
    }

error

like image 724
Swift2 Avatar asked Jul 06 '15 14:07

Swift2


1 Answers

The convenience initializer for UIButton has changed.

convenience init(type buttonType: UIButtonType)

Swift 3:

let btn = UIButton(type: .system) // note the lower case s

Swift 2.x:

let btn = UIButton(type: .System)
like image 67
JAL Avatar answered Nov 16 '22 02:11

JAL