Comment obtenir les coordonnées (x, y) d'un caractère dans une chaîne
J'ai besoin d'obtenir la coordonnée xy d'un caractère dans une chaîne, mais je n'ai pas trouvé de réponses à jour. Comment puis-je atteindre cet objectif? J'ai trouvé cet article ici: Swift: Comment trouver la position (x, y) d'une lettre dans un UILabel? mais .rangeOfString n'est plus disponible:
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)
}
Savez-vous comment le faire fonctionner à nouveau?
Réponses
Votre syntaxe Swift est vraiment ancienne (Swift 2). Changer range.startIndex
en range.lowerBound
. substringToIndex
est maintenant appelé substring (to: Index) mais il est obsolète, vous devez utiliser l'indice self[..<range.lowerBound]
. Btw, il n'est pas nécessaire d'utiliser String range(of: String)
si vous recherchez un index d'un caractère. Vous pouvez utiliser la méthode de collecte firstIndex(of: Element)
:
extension StringProtocol {
func characterPosition(character: Character, with font: UIFont = .systemFont(ofSize: 18.0)) -> CGPoint? {
guard let index = firstIndex(of: character) else {
print("\(character) is missed")
return nil
}
let string = String(self[..<index])
let size = string.size(withAttributes: [.font: font])
return CGPoint(x: size.width, y: 0)
}
}