Sunday, August 19, 2012

Custom Cell trong UItableView với XIB

Bài tut này sẽ hướng dẫn các bạn custom cell theo ý mình trong tableView.Kết quả sau khi các bạn thực hành theo bài tut sẽ như thế này:



Đầu tiên tạo project mới:




Sau khi tạo xong nó ra ri:


Bây giờ New File.. để thêm một view Controller mới hỉ:


Nhớ tick dô cái With XIB ở dưới nhé mấy bác!
Subclass of là: UIViewController

Nó ra ri:


Chừ tick dô file: CustomViewController.xib.
Các bác thêm một button (button ni chẳng qua là làm nên, để cho table view nó có bầu tròn 4 góc), chỉnh kích thước như hình vẽ:


Tiếp theo các bác cho một Table View dô..đè lên button nghe:



Qua phần code:

CustomViewController.h:


#import <UIKit/UIKit.h>

@interface CustomViewController : UIViewController<UITableViewDataSource, UITabBarDelegate>
{
    UIButton *btBackground;
    UITableView *tbView;
}

@property(nonatomic, retain) IBOutlet UIButton *btBackground;
@property(nonatomic, retain) IBOutlet UITableView *tbView;

@end


Nhớ là implement <UITableViewDataSourceUITabBarDelegate> dô nhé.


Phần CustomViewController.m

#import "CustomViewController.h"

@implementation CustomViewController

@synthesize tbView;
@synthesize btBackground;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self
    {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
   
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table Section
//Khi mà implement <UITableViewDataSourceUITabBarDelegate>, ít nhất phải có mấy hàm sau //nghe mấy bác, chứ không là nó báo warning đó:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end

Quay lại file CustomViewController.xib...Mấy bác kích chuột phải dô File's Owner...rồi kéo mấy cái tbView với btBackground dô đúng vị trí nghe:



Phần quan trọng, cái này mấy bác hay quên: kích chuột phải dô table view kéo dataSource với cái delegate dô chô File's Owner nhé:


Xong được một phần rồi, để đó xíu quay trở lại xúc tiếp...Chừ New File...tạo cái cell theo ý mình.
New File...chọn...:



Mấy bác nhớ Subclass là: UITableViewCell nhé:


Nó giống ri:



Viết code luôn hỉ:

CustomCell.h


#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell
{
    UILabel *lbTile;
    UILabel *lbSmallTitle;
}

@property(nonatomic, retain) IBOutlet UILabel *lbTile;
@property(nonatomic, retain) IBOutlet UILabel *lbSmallTitle;

@end

CustomCell.m

#import "CustomCell.h"

@implementation CustomCell

@synthesize lbTile;
@synthesize lbSmallTitle;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void) dealloc
{
    [lbTile release];
    [lbSmallTitle release];
    [super dealloc];
}


@end

Tiếp tục New File (tạo XIB để thiết kế cái cell theo ý mình đó)...




ok...Kích dô cái CustomCell.xib, xoá cái view đi, thay vào đó là cái Table View Cell:




ok..trên cell này bạn có thể thiết kế cell kiểu gì cũng được, tuỳ ý nhé: ở đây mình cho 2 label ở hàng, nó giống dậy:


Kích dô hai cái label kéo nó dài ra..cho đủ thấy chữ nhé bác. Chọn cái label dưới set màu chữ cho nó màu xám đi, chỗ phần Text Color bên trái:


Tiếp tục cho cell mình xuất hiện cái nút hình tròn có dầu > bên phải, chọn theo hình:
Chọn Table view Cell trước nhé, rùi kích dô Accessory bên phải nhé (cái nút này hàm ý nhắc người dùng bấm vào một cell là ra một view controller mới...):


Tiếp theo là 2 bước quan trọng nhé: để nối xib ni với lớp CustomCell:

1. Chọn cái Table View Cell đánh giống cái tên lớp dô vị trí như hình vẽ:


2. Chọn lớp CustomCell như hình vẽ:



Tiếp theo kích chuột phải dô Custom Cell, khung Objects á...kéo hai cái lbSmaillTitile (label phía dưới) với lbTitle (label phía trên) dô đúng vị trí nhé:


Xong lớp Custom Cell rồi đó mấy bác. ^^

Chừ dô CustomViewController.m quất code tiếp: 
Sửa 2 chỗ nửa thôi:
Nhưng trước tiên phải có cái này trên đầu cùng: #import "CustomCell.h"

1 là chỗ lày:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.btBackground.alpha=0.3; //cho background của button nó trong lại...giá trị càng nhỏ càng trong suốt.
    self.tbView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0];//Cho thèn table view mất màu luôn..
    self.view.backgroundColor=[UIColor blackColor]; //cho background của view controller màu đen
    self.btBackground.enabled=NO; // có bấm thèn button cũng không có dấu hiệu chi, nó chỉ background thui mà :)
}



và chỗ lày:

#pragma mark - Table Section

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    //Phần thiết lập nội dung cell

    static NSString *CellIdentifier = @"CustomCell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    
    if (cell == nil)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
        
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[CustomCell class]])
            {
                cell = (CustomCell *)currentObject;
                break;
            }
        }
    }
    
    cell.lbTile.text=@"Title Cell";
    cell.lbSmallTitle.text=@"Small Tiltle Cell";
    return cell;
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    
    return 15; //Số hàng trong một section, trong một bảng
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 61.0f; // chiều cao của hàng
}

Trước hết kiếp khổ đâu mấy bác, chừ làm cho View Controller: CustomViewController xuất hiện nửa là xong:

Dô file ni: AppDelegate.m  sửa lại cái hàm ni mấy bác:
Opp! import đã chớ, quất dòng ni dô đầu tiên nhé: #import "CustomViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    
CustomViewController *customVC=[[CustomViewController alloc] initWithNibName:@"CustomViewController" bundle:[NSBundle mainBundle]];
    [self.window addSubview:customVC.view];
    self.window.backgroundColor = [UIColor blackColor];
    
[self.window makeKeyAndVisible];
    return YES;
}


OK..Xong kiếp khổ rồi đó mấy bác...Mấy bác bấm Run chạy thử xem kết quả giống như hình đầu tiên không...Hi vọng sẽ giúp được mấy bác. Hẹn bài tút khác...Bye

@kent











No comments:

Post a Comment