質問

I set a custom MyView as background view for a UITableView:

MyView *noCellsView = [[MyView alloc] init];
[[noCellsView messageLabel] setText:@".........."];
[[self tableView] setBackgroundView:noCellsView];

It is displayed as background view, but the messageLabel is not set.

Why is that?

MyView.h

#import <UIKit/UIKit.h>

@interface MyView : UIView
@property (weak, nonatomic) IBOutlet NSObject *viewFromNib;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@end

MyView.m

#import "MyView.h"

@implementation MyView

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

        UIView* xibView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0];
        [xibView setFrame:[self bounds]];
        [self addSubview:xibView];
    }
    return self;
}
@end

MyView.xib The messageLabel is connected to the @property.

役に立ちましたか?

解決

Maybe you connect your outlets to MyView view in your nib but not to file owner. So that you end up with MyView view with another MyView as a subview. But the outlets are set only for the child MyView.

- (id)initWithFrame:(CGRect)frame
{
    ...
        // see that `owner:` parameter, it's the one who you want that `file owner` thing
        // to be, so if you'll bind outlets to file owner in xib and pass self to
        // this method for owner: parameter, you'll have outlets, binded to `file owner`
        // assigned to self.
        UIView* xibView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0]; // outlets are assigned to xibView, but not to self
    ...
    [self addSubview:xibView];
    ...
}

To make it work, you could bind (in Interface Builder) outlets to a file owner instead of MyView view. But, that would be a mess (you have MyView with MyView as a subview and the first one is some kind of a redundant proxy for the child one) and I'd suggest you to just create some other method or load view directly via -loadNibNamed:owner:options:.

// example method
+ (instancetype)loadFromXib
{
    // make sure that for that case you leave outlets binded to `MyView`, not to `file owner`.
    MyView *myView = ... //load from xib
    return myView;
}

// ...
// later on:
MyView *noCellsView = [MyView loadFromXib]; // vs [[MyView alloc] init];
[[noCellsView messageLabel] setText:@".........."];
[[self tableView] setBackgroundView:noCellsView];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top