保存。
三、代码中动态加载Table View Cell XIB:
打开oneViewController.h让oneViewController实现协议UITableViewDataSource,UITableViewDelegate,即:
oneViewController.m中实现下面的接口方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return20;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with
dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
staticNSString *CustomCellIdentifier =@"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
if (cell ==nil) {
NSArray *nib = [[NSBundlemainBundle]loadNibNamed:@"Cell" owner:selfoptions:nil];
// if ([nib count] > 0) {
// cell = self.tableViewCell;
// } else {
// NSLog(@"failed to load CustomCell nib file!");
// }
cell = [nib objectAtIndex:0]; // 注释掉的和该句是两种方式,在这里两种方式都行。但是如果没有上面红色处(图XXX)的拖拽连接过程,这里只能使用nib objectAtIndex方式。
}
NSUInteger row = [indexPathrow];
NSLog(@"++++++++++++++ jonesduan %s, cell row:%d", __func__, row);
UILabel *cellLabel = (UILabel *)[cellviewWithTag:1];
cellLabel.text = [NSStringstringWithFormat:@"cell index: %d", row];
UIButton *cellButton = (UIButton *)[cellviewWithTag:2];
[cellButton setTitleColor:[UIColorredColor]forState:UIControlStateNormal];
[cellButton setTitleColor:[UIColororangeColor]forState:UIControlStateHighlighted];
[cellButton setTitle:@"Press me!"forState:UIControlStateNormal];
[cellButton setTitle:@"Pressed!"forState:UIControlStateHighlighted];
return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Modified by jonesduan.
return80;
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.labelsetBackgroundColor:[UIColorgrayColor]];
[self.buttonsetTitleColor:[UIColorgreenColor]forState:UIControlStateNormal];
[self.buttonsetTitleColor:[UIColororangeColor]forState:UIControlStateHighlighted];//这里控制的是oneViewController.xib中的label和button,前面已经拖拽连接过。
}
这样完成后。CMD + R运行一下看看,发现界面如下图所示:
OK,成功!
总结:通过xib自定义view比较重要的一点就是这个view被哪个view controller使用,比如xxxViewController,就要在identity inspector中Custom Class指定对应的加载类为xxxViewController,然后选中File's owner(中间大窗口中的Placeholders下),并切换到connections inspector将Outlets下面的对象与中间大窗口中的Objects(与Placeholders同级别,在Placeholders下面)下的根视图相连接。最后别忘了Table View的dataSource和delegate均与File's owner相拖拽进行连接。
APPLE开发最不习惯的就是拖拽连接,在此记录一下作为个人参考,免得以后忘记了。
demo下载地址:http://download.csdn.net/detail/duanyipeng/4063778
摘自 Code Heaven
联系客服