Stevik
Stevik

Reputation: 1152

Swift coordinates of a pressed button

I'm working on a tic tac toe game (3x3), so I have 9 buttons and what I want to do is to get coordinates of a button which user had pressed and insert an image on the place of the button.

Example:

@IBOutlet weak var button1Outlet: UIButton!
@IBAction func button1Action(sender: AnyObject) {

        let imageName = "IMG.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)
        imageView.frame = CGRect(x: 0, y: 0, width: 90, height: 90)
        view.addSubview(imageView)


}

I know I can get coordinates of the button using button1Outlet.center , but I need something like this.center to avoid hardcoding it for every button.

Upvotes: 0

Views: 613

Answers (2)

Firo
Firo

Reputation: 15566

When a button is clicked it is passed as a parameter to the function. Just use the sender.

// Change sender to a UIButton type
@IBAction func button1Action(sender: UIButton) {
    // ... Setup your views

    // Set same frames
    imageView.frame = sender.frame
    view.addSubview(imageView)

    // If you want to remove the button
    sender.removeFromSuperview()
}

Upvotes: 1

tskulbru
tskulbru

Reputation: 2346

You can cast the sender to a UIButton which you then can access any frame related methods on.

(sender as UIButton).center

Upvotes: 2

Related Questions