Wim Haanstra
Wim Haanstra

Reputation: 5998

setValue:forKey with struct

I have a question about the setValue:forKey method on (for example) a UIView.

I have the following code:

let label = UILabel()
label.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10)
let margins = label.valueForKey("layoutMargins")

In the debugger the type of margins is (AnyObject?) with the value Some.

If I use the variable margins to set the value on a UIView, this works as expected:

let label2 = UILabel()
label2.setValue(margins, forKey: "layoutMargins")

But if I try to set a UIEdgeInsets struct directly using the setValue:forKey method, this of course doesn't work, because it expects an AnyObject and not a struct.

label2.setValue(UIEdgeInsetsMake(5,5,5,5), forKey: "layoutMargins")

Is it possible for me to wrap this UIEdgeInsets in something or cast it to something to be able to set the value using that setValue method?

Upvotes: 2

Views: 702

Answers (1)

DarkDust
DarkDust

Reputation: 92384

You need to wrap the UIEdgeInsets with NSValue. iOS already provides the necessary support via +[NSValue valueWithUIEdgeInsets:], so the solution should look like this:

label2.setValue(NSValue(UIEdgeInsets: UIEdgeInsetsMake(5,5,5,5)), forKey: "layoutMargins")

Upvotes: 3

Related Questions