Reputation: 3602
I am trying to add buttons programatically to a view, but they seem to be unexpectedly positioned. Can anyone tell what is wrong:
for var i = 0; i < 10; i++ {
let button = UIButton(type: UIButtonType.Custom) as UIButton
let x1 = i * 20
let x2 = i * 20 + 15
button.frame = CGRectMake(CGFloat(x1), 20, CGFloat(x2), 40)
button.backgroundColor = UIColor.blueColor()
button.titleLabel?.textAlignment = .Center
button.setTitle(String(i + 1), forState: .Normal)
self.view.addSubview(button)
}
Upvotes: 0
Views: 30
Reputation: 229
Third argument in CGRectMake is width, not x2. So you should pass 15 (or what your desired width of button is). Also consider using swift version of CGRect initializer - CGRect(x: y: width: height: ) - as it uses named parameters
Upvotes: 1