我想创建一个区段标头,它加载一个nib文件并将其设置为标头UIView。这个nib文件还将有一个关联的类,其中的outlets和actions是连接到的,所以我想像normal一样加载带有nib的类。
我在网上搜索,找到了几个类似的答案,但我找不到任何适合我的答案。在尝试了几天之后,我设法让视图正确显示,但它没有做任何事情,尽管添加了连接并告诉文本以不同的方式显示。
例如,如果它是init with nil,那么它应该清除部分标题文本,但它仍然显示相同的文本,尝试更改它也不会反映出来,也不会触发与按钮的任何连接。
下面是我的视图控制器
@interface ADUNewRowHeaderViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *sectionTitleField;
@property (strong, nonatomic) IBOutlet UIButton *addRowBtn;
@property(strong,nonatomic) NSString* sectionTitle;
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
title:(NSString*) titleOrNil;
@end下面是实现
@implementation ADUNewRowHeaderViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil title:(NSString *)titleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
if(titleOrNil != nil)
{
[self setSectionTitle:titleOrNil];
}
else
{
[self setSectionTitle:@""];
}
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)setSectionTitle:(NSString *)sectionTitle
{
_sectionTitle = sectionTitle;
[[self sectionTitleField] setText:sectionTitle];
}
@end在实际的表视图控制器中,它被列为
@property(nonatomic, strong) ADUNewRowHeaderViewController* secHeader;并在viewDidLoad下的实现文件中作为
[self setSecHeader:[[ADUNewRowHeaderViewController alloc] initWithNibName:nil bundle:nil title:nil]];
[[[self secHeader] addRowBtn] addTarget:self action:@selector(addNewRow:) forControlEvents:UIControlEventTouchUpInside];和
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
return [[self secHeader] view];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return [[self secHeader] view].bounds.size.height;
}这是操作的方法声明
- (IBAction)addNewRow:(id)sender;发布于 2013-04-28 05:12:42
您应该创建一个UIView子类,而不是UIViewController子类。.m将包含:
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self setUp];
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self setUp];
}
- (void)setUp
{
[[NSBundle mainBundle] loadNibNamed:@"YourNibName" owner:self options:nil];
CGRect frame = self.frame;
self.view.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
[self addSubview:self.view];
... do other initialisations here ...
}和.h
@interface ADUNewRowHeaderView : UIView
@property (nonatomic, strong) IBOutlet UIView* view;然后在XIB中:像往常一样,使文件拥有类ADUNewRowHeaderView。并将XIB的顶级视图的引用出口连接到上面的view属性(即在文件的所有者中)。
然后,您可以将一个XIB子类放在另一个UIView上(作为一个UIView,您可以将它的类设置为ADUNewRowHeaderView),或者在代码中实例化并作为子视图添加。
(或者,您可以创建UIView及其子视图(按钮、标签...)在代码中;那么您就不需要XIB了。但是,只有当UIView很简单,几乎没有自己的逻辑,并且没有几个易于在代码中布局的UI元素时,这才能起作用。)
https://stackoverflow.com/questions/16256403
复制相似问题