JohnDole
JohnDole

Reputation: 565

Get position of an UIView in an UIImageView

I have the following:

enter image description here

(1) Is a Giphy. I want to be able to move the giphy to the trash. I get the coordinates of the giphy with:

    print("position of finger in moving giphy")
    let position = gesture.location(in: imageViewImageTaken)

I struggle to get the position of my "trash" icon. This icon is a subview of my UIImageView, which is a photo.

I tried to get the position of the "trash" icon with:

let positionTrash = imageViewBin.convert(imageViewBin.bounds, to: imageViewImageTaken)

But when I move my finger to the trash icon and get the coordinates of (1) it does not match.

How can I correctly receive the position of (2)?

Upvotes: 0

Views: 460

Answers (1)

Sweeper
Sweeper

Reputation: 271050

Since frame is the x, y, width, height of a view in its superview's coordinate system, you can use frame to get the x, y, width, height of the trash icon in the image view's coordinate system. There is no need to use convert:

let trashFrame = imageViewBin.frame

You seem to have another misunderstanding about how to check whether the finger is touching the trash. To do this, you need to check whether a CGRect (trashFrame) contains a CGPoint (position). This can be done using CGRect.contains:

if trashFrame.contains(position) {
    print("The finger is on the trash icon!")
}

Alternatively, get the location of the finger and check if it is in the bounds of the trash:

let position = gesture.location(in: imageViewBin)
if imageViewBin.bounds.contains(position) {

}

Upvotes: 2

Related Questions