transportation - the swift programming language pdf




NSString boundingRectWithSize: opciones: atributos: contexto: ¿no se puede usar en Swift? (4)

Alternativamente, podrías lanzarlo en una NSString

if let ns_str:NSString = str as NSString? {

   let sizeOfString = ns_str.boundingRectWithSize(
                                 CGSizeMake(self.titleLabel.frame.size.width, CGFloat.infinity), 
                                 options: NSStringDrawingOptions.UsesLineFragmentOrigin, 
                                 attributes: [NSFontAttributeName: lbl.font], 
                                 context: nil).size
}

Me sale el error ...

Could not find an overload for 'init' that accepts the supplied arguments

... cuando trato de usar ...

extension UIFont {
  func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
    NSString(string).boundingRectWithSize(CGSize(width, DBL_MAX),
                                          options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                                          attributes: [NSFontAttributeName: self],
                                          context: nil).size
  }
}

¿ NSString no admite este método, o estoy desordenando la sintaxis?


El último Swift:

import UIKit

extension UIFont {
    func sizeOfString(string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                                             options: .usesLineFragmentOrigin,
                                                             attributes: [NSFontAttributeName: self],
                                                             context: nil).size
    }
}

Puedes usar el puente objetivo-c

let lblRegisterlinkWidth: CGFloat = lblRegisterLink.text!._bridgeToObjectiveC().boundingRectWithSize(lblRegisterLink.frame.size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : lblRegisterLink.font], context: nil).size.width

Último Swift

func sizeOfString (string: String, constrainedToHeight height: Double) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: DBL_MAX, height: height),
                                                 options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                 attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)],
                                                 context: nil).size
}






swift