gpt4 book ai didi

ios - UILabel 中字母的 Swift : How do I find the position(x, y)?

转载 作者:可可西里 更新时间:2023-11-01 00:59:27 25 4
gpt4 key购买 nike

我试图找到一个字母在 labelText 中的位置。Objective 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);

请有人告诉我我们如何在 swift 中编写上面的代码?我发现计算字符串的范围有点困难。

最佳答案

我最终会推荐以下变体:

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(",")

关于ios - UILabel 中字母的 Swift : How do I find the position(x, y)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37475593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com