我试图在labelText中找到一个字母的位置。 目标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中编写上述代码?我发现计算字符串的范围有点困难。
答案 0 :(得分:2)
我最后会推荐以下变体:
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(",")
答案 1 :(得分:1)
试试这段代码::
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
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)")
答案 2 :(得分:0)
将此转换为swift语法
时,没有任何改变var range: NSRange = "Good,Morning".rangeOfString(",")
var prefix: String = "Good,Morning".substringToIndex(range.location)
print(prefix) //Good
答案 3 :(得分:0)