Swift - 使用 CGSize 执行选择器

Swift - perform selector with CGSize

我有这个电话:

myObject.perform(Selector("setCellSize:"), with: CGSize(width: 50.0, height: 50.0))

在class里面我有:

func setCellSize(_ size: CGSize) {
    print(size)
    self.itemSize = size
}    

该方法被正确调用,但它打印 (0.0, 7.2911220195564e-304)。怎么了?

CGSize 不是对象。这是一个结构。您正在打印传递给 setter 的乱码。该功能 用于对象。

perform(_:with:)NSObjectProtocol

的方法

Sends a message to the receiver with an object as the argument.

特别是,

aSelector should identify a method that takes a single argument of type id. For methods with other argument types and return values, use NSInvocation.

如果你真的必须通过这个方法传递一个CGSize那么你可以 将其包装成 NSValue:

let value = NSValue(cgSize: CGSize(width: 50.0, height: 50.0))
myObject.perform(#selector(setCellSize(_:)), with: value)


func setCellSize(_ size: NSValue) {
    print(size.cgSizeValue)
}