I get the error...
Could not find an overload for 'init' that accepts the supplied arguments
...when I try to use...
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
}
}
Does NSString
not support this method anymore, or am I messing up on the syntax?
The initializers expect named arguments.
extension UIFont {
func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
return NSString(string: string).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self],
context: nil).size
}
}
Note: String
s can be cast to NSString
s.
extension UIFont {
func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self],
context: nil).size
}
}
or
extension UIFont {
func sizeOfString (string: NSString, constrainedToWidth width: Double) -> CGSize {
return string.boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self],
context: nil).size
}
}
--
UPDATED
For Swift 4 syntax
extension UIFont {
func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
return NSString(string: string).boundingRect(
with: CGSize(width: width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: self],
context: nil).size
}
}
Alternatively you could cast it into an 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
}
Latest 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
}
}
Latest 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With