简体   繁体   中英

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
        }
    }

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 (eg 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM