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

时间:2016-05-27 05:38:44

标签: ios iphone swift position nsrange

我试图在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中编写上述代码?我发现计算字符串的范围有点困难。

4 个答案:

答案 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)

安全查找范围的方法是使用if-let语句,因为rangeOfString可能会返回nil值。请完成以下代码:

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

以上代码的结果为:  enter image description here