【问题标题】:load another UIView from same xib to add as subview从同一个 xib 加载另一个 UIView 以添加为子视图
【发布时间】:2014-11-29 12:59:58
【问题描述】:

我的 UITableView 是 Storyboard。 我尝试在 Xib 中创建 UITableViewCell 并将其注册到 UITableView 中:

-(void)viewDidLoad{
    [super viewDidLoad];
    UINib *nib = [UINib nibWithNibName:@"FlipperTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"fliperCell"];
}

效果很好。

但是这个单元格内部必须有一个视图,并在按下第一个视图上的按钮时将其翻转到另一个视图。

我在同一个 xib 中创建另外两个视图。 文件的所有者是 FliperTableViewCell 类。第一个视图的类是 FliperTableViewCell。

但现在无法弄清楚如何将第二个视图 (UIView) 添加为由表视图加载的第一个视图 (UITableViewCell) 中的子视图。 我尝试从 loadNibNamed: 获得第二个视图,但它变成了无限循环。

@implementation FlipperTableViewCell
-(id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]){
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] objectAtIndex:1]];
    }
    return self;
}

从同一个 xib 获取第二个视图并在加载第一个视图时将其添加为子视图的另一种方法是什么?

【问题讨论】:

  • 您是否尝试过创建多个视图并将它们连接到 xib 中?它应该在加载时为您创建并连接它们。
  • 我编辑了我的问题并添加了 xib 图像。当 tableView 将创建 FlipTableViewCell 类的实例时,在这种情况下,我想获得第二个视图的访问权限。我的问题是我不知道如何从第一个实例中获取第二个视图。
  • 将“face”和“View”放入 flipperCell,并隐藏它们。然后,在运行时,取消隐藏您想要看到的响应按钮按下的那个。这样做,所有东西都已经挂在 xib 中了,所以你不需要做任何事情来加载它。
  • 似乎这是唯一的方法。为了方便创建视图,我试图将单元格拆分为多个视图。感谢您的回答。

标签: ios objective-c uitableview xib


【解决方案1】:

替换后问题解决了

[self.tableview registerNib:nib forCellReuseIdentifier:@"FlipperTableViewCell"];

[self.tableview registerClass:[FlipperTableViewCell class] forCellReuseIdentifier:@"FlipperTableViewCell"];

然后从 xib 中删除第一个视图并重写 FlipperTableViewCell 以在代码中启动

#import "FlipperTableViewCell.h"

@interface TableViewCell ()
@property (nonatomic, strong) UIView *firstView;
@property (nonatomic, strong) UIView *secondView;
@end

@implementation FlipperTableViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
        self.firstView = nibObjects[0];
        self.secondView = nibObjects[1];
        [self.contentView addSubview:self.firstView];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

// this is for test changing views
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    if (self.contentView.subviews[0] == self.firstView){
        [self.firstView removeFromSuperview];
        [self.contentView addSubview:self.secondView];
    }
    else{
        [self.secondView removeFromSuperview];
        [self.contentView addSubview:self.firstView];
    }
}

@end

【讨论】:

    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多