Convert CGFloat to NSNumber in Swift

2019-06-14 21:33发布

I have an extension in Swift that holds some properties which are CGFloat's. The problem is that I don't know how to get the store the CGFloat value as a NSNumber using the associated objects

Here is the code I have that doesn't work but it details what I want to do:

var scaledFontSize: CGFloat {
    get {
        guard let fontSize = objc_getAssociatedObject(self, &AssociatedKeys.scaledFontSize) as? NSNumber else {
            //Set it
            let scaledFont:CGFloat = VGSizeValues.getValueFromValue(self.font.pointSize);
                //Fails here
            objc_setAssociatedObject(self,&AssociatedKeys.scaledFontSize, NSNumber( scaledFont),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return scaledFont;
        }
        return CGFloat(fontSize.doubleValue);

    }
}

Does anyone way to work around this?

4条回答
乱世女痞
2楼-- · 2019-06-14 21:47

For Swift 3.1

var final_price: CGFloat = 12.34
let num = final_price as NSNumber
查看更多
趁早两清
3楼-- · 2019-06-14 21:49

For me this is worked.

self.configuration.cellHeight as NSNumber!
查看更多
ゆ 、 Hurt°
4楼-- · 2019-06-14 21:53

In Swift 3.0

let myFloat : CGFloat = 1234.5

let myNumber = NSNumber(value: Float(myFloat))

or

let myNumber = NSNumber(value: Double(myFloat))

In Swift 2

let myNumber = NSNumber(double: myFloat.native)

or

let myNumber = NSNumber(double: Double(myFloat))

or

let myNumber = NSNumber(float: Float(myFloat))
查看更多
孤傲高冷的网名
5楼-- · 2019-06-14 22:05

Swift 3

let myNumber = NSNumber(value: Float(myCGFloat))

查看更多
登录 后发表回答