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

这一生的挚爱 提交于 2020-01-15 03:46:27

问题


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 .


回答1:


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



回答2:


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

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



回答3:


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



回答4:


A safe way to find range is to use if-let statement since rangeOfString may return a nil value. 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:



来源:https://stackoverflow.com/questions/37475593/swift-how-do-i-find-the-positionx-y-of-a-letter-in-a-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!