如何在xib中访问UITextLabel?

时间:2014-03-08 14:41:05

标签: ios uiview properties xib

我将自定义MyView设置为UITableView的背景视图:

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

它显示为背景视图,但未设置messageLabel

为什么?

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 messageLabel连接到@property。

1 个答案:

答案 0 :(得分:3)

也许您将自己的商店连接到笔尖中的MyView视图,但不是file owner。因此,您最终将MyView视图与另一个MyView视为子视图。但是只为孩子设置了出口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];
    ...
}

要使其正常工作,您可以将(在Interface Builder中)出口绑定到file owner而不是MyView视图。但是,这将是一个烂摊子(你有MyView MyView作为子视图,第一个是某种冗余代理的孩子一个)我建议你只是创建一些其他方法或加载视图直接通过-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];