2015-07-06 16 views
11

Sto cercando di inizializzare un UIButton di programmazione, ma vedere uno di questi errori:iOS 9 UIButton Inititalization

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

o

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

+0

'UIButton (tipo: ...) '? – JAL

+0

Non ti capisco – Swift2

+0

Vedere la risposta che ho appena postato. – JAL

risposta

33

L'inizializzatore convenienza per UIButton è cambiato.

convenience init(type buttonType: UIButtonType)

Swift 3:

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

2.x Swift:

let btn = UIButton(type: .System) 
+0

Grazie mille – Swift2

-2

In iOS 9 convenienza init è stato modificato per buttonWithType. Non è possibile utilizzare

let button = UIButton.buttonWithType(UIButtonType.System) 

invece utilizzare

let button = UIButton(type: UIButtonType.System) 

Qui di seguito è la sintassi:

Screenshot

0

iOS 10 Xcode 8 .....

let button = UIButton(type: .system) // note the lower case s 
    button.setTitle("Dismiss", for: UIControlState()) 
    button.backgroundColor = UIColor.white 
    let buttonWidth: CGFloat = alertWidth/2 
    let buttonHeight: CGFloat = 40 
    button.frame = CGRect(x: alertView.center.x - buttonWidth/2, y: alertView.center.y - buttonHeight/2, width: buttonWidth, height: buttonHeight) 
    button.addTarget(self, action: #selector(ExampleIIIViewController.dismissAlert), for: UIControlEvents.touchUpInside) 

    alertView.addSubview(button)