简体   繁体   English

Swift:如何在UILabel中找到字母的位置(x,y)?

[英]Swift : How do I find the position(x,y) of a letter in a UILabel?

I am trying to find the position of a letter in a labelText . 我试图在labelText中找到字母的位置。 The code in Objective C is 目标C中的代码是

NSRange range = [@"Good,Morning" rangeOfString:@","];
NSString *prefix = [@"Good,Morning" substringToIndex:range.location];
CGSize size = [prefix sizeWithFont:[UIFont systemFontOfSize:18]];
CGPoint p = CGPointMake(size.width, 0);
NSLog(@"p.x: %f",p.x);
NSLog(@"p.y: %f",p.y);

Please someone tell me how we write the above code in swift ? 请有人告诉我我们如何迅速编写以上代码? I am finding it bit difficult to calculate range of a string . 我发现很难计算一个字符串的范围。

I finally would recommend following variant: 我最终会建议以下变体:

extension String {

    func characterPosition(character: Character, withFont: UIFont = UIFont.systemFontOfSize(18.0)) -> CGPoint? {

        guard let range = self.rangeOfString(String(character)) else {
            print("\(character) is missed")
            return nil
        }

        let prefix = self.substringToIndex(range.startIndex) as NSString
        let size = prefix.sizeWithAttributes([NSFontAttributeName: withFont])

        return CGPointMake(size.width, 0)
    }
}

Client's code: 客户代码:

let str = "Good,Morning"
let p = str.characterPosition(",")

Try this code:: 试试这个代码:

let range : NSRange = "Good,Morning".rangeOfString(",");
let prefix: NSString = "Good,Morning".substringToIndex(range.location);
let size: CGSize = prefix.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(18.0)])
let p : CGPoint = CGPointMake(size.width, 0);
NSLog("p.x: %f",p.x)
NSLog("p.y: %f",p.y)

Swift 4 斯威夫特4

    let range: NSRange = ("Good,Morning" as NSString).range(of: ",")
    let prefix = ("Good,Morning" as NSString).substring(to: range.location)//"Good,Morning".substring(to: range.location)
    let size: CGSize = prefix.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18.0)])
    let p = CGPoint(x: size.width , y: 0)
    print("p.x: \(p.x)")
    print("p.y: \(p.y)")

Nothing really changes when converting this to swift just the syntax 将其转换为快速语法时,什么都没有真正改变

var range: NSRange = "Good,Morning".rangeOfString(",")
var prefix: String = "Good,Morning".substringToIndex(range.location)
print(prefix) //Good

A safe way to find range is to use if-let statement since rangeOfString may return a nil value. 查找范围的一种安全方法是使用if-let语句,因为rangeOfString可能返回nil值。 Go through the following code: 通过以下代码:

if let range = str.rangeOfString(",") {
    let prefix = str.substringToIndex(range.startIndex)
    let size: CGSize = prefix.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14.0)])
    let p = CGPointMake(size.width, 0)
}

Above code gives the result as: 上面的代码给出的结果为: 在此处输入图片说明

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

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