开发者

InitWithFrame not executed if view is a property

开发者 https://www.devze.com 2023-03-12 22:23 出处:网络
I have GraphicView class that inherits from UIView. Its initWithFrame method is: @implementation GraphicsView

I have GraphicView class that inherits from UIView. Its initWithFrame method is:

@implementation GraphicsView

- (id)initWithFrame:(CGRect)frameRect
{
    self = [super initWithFrame:frameRect];

    // Create a ball 2D object in the upper left corner of the screen
    // heading down and right
    ball = [[Object2D alloc] init];
    ball.position = [[Point2D alloc] initWithX:0.0 Y:0.0];
    ball.vector = [[Vector2D alloc] initWithX:5.0 Y:4.0];

    // Start a timer that will call the tick method of this class
    // 30 times per second
    timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/30.0)
                                             target:self
                                           selector:@selector(tick)
                                           userInfo:nil
                                            repeats:YES];

    return self;
}

Using Interface Builder I've added a UIView (class = GraphicView) to ViewController.xib. And I've added GraphicView as a property:

@interface VoiceTest01ViewController : UIViewController {

    IBOutlet GraphicsView *graphView;
}

@property (nonatomic, retain) IBOutlet GraphicsView *graphView;

- (IBAction)btnStartClicked:(id)sender;
- (IBAction)btnDrawTriangleClicked:(id)sender;

@end

But with this code doesn't work, I need to call [graphView initWithFrame:graphView.frame] to make it works.

- (void)viewDidLoad {
    [super viewDidLoad];
    isListening = NO;
    aleatoryValue = 10.0f;

    // Esto es necesario para inicializar la vista
    [graphView initWithFrame:graphView.frame];

}

Am I doing well? Is there a better way to do that开发者_如何学Python?

I don't know why initWitFrame is not called if I add GraphicView as a property.


initWithFrame is not called when loading from a NIB, it's initWithCoder instead.

If you may be using both loading from a NIB and programmatic creation, you should make a common method (initCommon maybe?) that you would call from both initWithFrame and initWithCoder.


Oh, and your init method is not using the recommended practices:

- (id)initWithFrame:(CGRect)frameRect
{
    if (!(self = [super initWithFrame:frameRect]))
        return nil;

    // ...
}

You should always check the return value of [super init...].

0

精彩评论

暂无评论...
验证码 换一张
取 消