Reputation: 31
I'm new doing Cocoa Touch but I worked whit java swing, I made what I suppose draw to buttons on the screen, one on the left (green) and other on the right (blue), but I only see the blue one the other is missing. It's a class of a view with two buttons on it.
import UIKit
class MouseClick: UIView {
//MARK: Atributes
var clicks = [UIButton]()
//MARK: Initializer
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
//let bounds = UIScreen.mainScreen().bounds
let button = UIButton()
// x: start of x in frame, y: start of y in frame width:half screen, height:full screen
let leftButtonFrame = CGRect(x: frame.origin.x, y:frame.origin.y, width: frame.size.width/2.0, height:frame.size.height)
// x: start of x in frame plus the half, y: start of y in frame width:half screen, height:full screen
let rigthButtonFrame = CGRect(x: frame.origin.x + frame.size.width/2.0, y: frame.origin.y, width: frame.size.width/2.0, height: frame.size.height)
//test action (only prints)
button.addTarget(self, action: "clickAction:", forControlEvents: .TouchDown)
clicks = [button, button]
clicks[0].frame = leftButtonFrame
clicks[1].frame = rigthButtonFrame
clicks[0].backgroundColor = UIColor.greenColor()
clicks[1].backgroundColor = UIColor.blueColor()
addSubview(clicks[0])
addSubview(clicks[1])
}
override func layoutSubviews() {
// Set butons(clicks) size, width:half screen, height:full screen
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0.0, y: 0.0, width: frame.size.width/2.0, height: CGFloat(buttonSize))
// set x position for every button in clixk
for (index, button) in clicks.enumerate() {
buttonFrame.origin.x = CGFloat(index) * frame.size.width/2.0
button.frame = buttonFrame
}
}
override func intrinsicContentSize() -> CGSize {
let heigth = Int(frame.size.height)
let width = Int(frame.size.width)
return CGSize(width: width, height: heigth)
}
//MARK: Clicks actions
func clickAction(button: UIButton)
{
var n = clicks.indexOf(button)!
if n == 0
{
print("leftie")
} else
{
print("rightie")
}
}
}
the resulting image here,
]1
Upvotes: 0
Views: 72
Reputation: 4966
The problem is that you initialize only one button. The 'clicks' array contains two references pointing to the same Button. This is why you only see one on Screen.
let button = UIButton()
let button2 = UIButton()
. . .
clicks = [button, button2]
Now you have two buttons.
Upvotes: 1