Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

iphone - how to create custom tableViewCell from xib

I want to create a custom TableViewCell on which I want to have UITextField with editing possibility. So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx!

//EditCell. h

#import <UIKit/UIKit.h>


@interface EditCell : UITableViewCell
{
    IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end

//EditCell.m

#import "EditCell.h"


@implementation EditCell
@synthesize editRow;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidUnload 
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
    self.editRow = nil; 
}
@end

//in my code

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                reuseIdentifier:CellIdentifier] autorelease];
    }
cell.editRow.text = @"some text to test";
return cell;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do not use UITableViewCell's initializer, but make the cell load from your nib:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"EditCell";

    EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil];
        cell = (EditCell *)[nib objectAtIndex:0];
    }
    cell.editRow.text = @"some text to test";
    return cell;
}

Of course, you need to specify the correct nib name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...