Initialization of controls in custom uiview

2019-08-06 03:48发布

I've created a custom uiview in IB and set the class for it.

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface myView : UIControl {
    IBOutlet UITextView *textView;
}
@end

#import "myView.h"

@implementation myView

- (void)commonInit
{
    [textView setText:@"lajsdfklasdfjl"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self commonInit];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self commonInit];
    }
    return self;
}

@end

I put a textview with text on this view in IB and linked it to IBOutlet IUTextView *textView. When I drag this custom view on my UIViewController (from classes tab in IB's library) the view is empty. - (id)initWithCoder:(NSCoder *)aDecoder is calling but the textView is null. What is wrong? Thanks

2条回答
男人必须洒脱
2楼-- · 2019-08-06 04:07

As far as I remember, the hierarchy is not properly set up in init, as the properties can only be set after init has finished.

You want to use

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self commonInit];
}

instead and remove the initWithCoder: thing altogether.

As a side note, you should let your class names begin with upper case letters.

查看更多
放我归山
3楼-- · 2019-08-06 04:10

There should be nothing stopping you from using a custom UIViewController which has methods built in for initializing or deallocating the UIView that it contains. I found this to be a simpler solution. For example, you can set up your custom UIViewController using a nib with a UIView, then make sure your File's Owner is set to the custom class.

You can then remove the following 3 instance methods

- (void)commonInit
- (id)initWithCoder:(NSCoder *)aDecoder
- (id)initWithFrame:(CGRect)frame

and in your custom UIViewController class use initWithNibName as below

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.frame = CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height);
    }
    return self;
}

This initWithNibName instance method will be called automatically when you alloc your custom UIViewController class like this

CustomUIViewController *vc = [[CustomUIViewController alloc] init];

Put a break point in initWithNibName and you will see it called.

查看更多
登录 后发表回答