Overriding uiviewcontroller's view property with Swift

217 views
Skip to first unread message

Zipette

unread,
Jan 29, 2015, 5:44:49 AM1/29/15
to swift-l...@googlegroups.com
Hello,
I want to override my uiviewcontroller's view property. I found the right way to do it in ObjectiveC here http://travisjeffery.com/b/2012/12/overriding-uiviewcontrollers-view-property-done-right/ but how can I traduct this code in Swift ?

here is the code I would want to traduce in Swift :
// ViewController.h @interface ViewController : UIViewController @property (strong, nonatomic) UIScrollView *view; @end // ViewController.m @implementation ViewController @dynamic view; - (void)loadView { self.view = [[UIScrollView alloc] initWithFrame:UIScreen.mainScreen.applicationFrame]; }  
@end

Thanks a lot for your help
Vins

Jens Alfke

unread,
Jan 29, 2015, 11:41:58 AM1/29/15
to Zipette, swift-l...@googlegroups.com
That Obj-C code doesn't look right. There's no need to override the 'view' property at all, since the superclass already defines it. Just set its value in the -loadView method. 

What Travis's example seems to do is exploit behavior that, at least in the current Obj-C compiler, lets you alter the class of an inherited property. I guess this lets you avoid type-casts, but IMHO it's a hack — I've been coding in Obj-C and Cocoa since 2000 and I've never seen anyone do this before; I have my doubts whether the language design even intended for this to be legal.

If you really want to do this in Swift, the equivalent of @dynamic is @NSManaged, but according to Apple's docs this is only for use in CoreData NSManagedObject subclasses, so I don't know if it works outside of that:

Like the @dynamic attribute in Objective-C, the @NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike @dynamic, the @NSManaged attribute is available only for Core Data support.

—Jens
Reply all
Reply to author
Forward
0 new messages