简体   繁体   English

如何在Swift中比较两点

[英]How to compare two points in Swift

I have a UITextView which contains text and images. 我有一个包含文本和图像的UITextView I also have a CGPoint array containing coordinates of images added by a user in the UITextFied . 我也有一个CGPoint数组,其中包含用户在UITextFied添加的图像的坐标。 Whenever texts in the UITextView changes (addition or deletion), I get the position of the cursor which is a CGPoint object. 每当UITextView文本发生更改(添加或删除)时,我都会获得CGPoint对象的光标位置。

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. 现在,我想遍历CGPoint数组以查找在光标位置之后的同一行或下面的行中有多少图像。 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 处理Y位置

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 )). 要处理X位置( lineHeight是一个常量,具体取决于您的大小写和图像的大小,您可能会lineHeight一些较低的常量值(例如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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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