Swift:如何找到UILabel中字母的位置(x,y)? [英] Swift : How do I find the position(x,y) of a letter in a UILabel?

查看:274
本文介绍了Swift:如何找到UILabel中字母的位置(x,y)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在labelText中找到字母的位置. 目标C中的代码是

I am trying to find the position of a letter in a labelText . The code in Objective C is

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

客户代码:

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

这篇关于Swift:如何找到UILabel中字母的位置(x,y)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆