Michael Woyo
Michael Woyo

Reputation: 148

How to compare two points in Swift

I have a UITextView which contains text and images. I also have a CGPoint array containing coordinates of images added by a user in the UITextFied. Whenever texts in the UITextView changes (addition or deletion), I get the position of the cursor which is a CGPoint object.

Now I want to loop through my CGPoint array to find how many images fall after the cursor position whether on the same line or lines below. How do I go about it?

Any help would be very much appreciated.

Sure:

var cursor = message.caretRectForPosition(message.selectedTextRange?.end).origin;    
for i in 0...emoji1.count-1 {
        if ((cursor.x > emoji_pt[i].x)  && (cursor.y <= emoji_pt[i].y)) {
            continue;
        }
        else {
            //the emoji is after the cursor.
            // Return the index and process all images after that index
        }
    }

Upvotes: 0

Views: 1205

Answers (1)

Sulthan
Sulthan

Reputation: 130072

To handle the Y position

Bool onPreviousLine = (emoji_pt[i].y < cursor.y)

To handle the X position (lineHeight being a constant depending on your case and the size of images, you could probably get away with some low constant value (e.g. 1.0)).

Bool onTheSameLine = abs(Double(emoji_pt[i].y - cursor.y)) < Double(lineHeight / 2)
Bool beforeX = (emoji_pt[i].x < cursor.x)

Together

if onPreviousLine || (onTheSameLine && beforeX) {
    continue
}

Upvotes: 1

Related Questions