用代码自定义UITableViewCell

2015-08-14  本文已影响1782人  LeoAu

最近开始使用代码写UI,所以在网上寻找一些可用的案例参考,自己写了一个案例

参考案例地址:http://jslim.net/blog/2013/03/22/ios-create-uitableview-with-custom-cell-programmatically/

AUCustomCell.h

#import <UIKit/UIKit.h>

@interface AUCustomCell : UITableViewCell

@property (nonatomic, strong) UILabel *descriptionLabel;@end

AUCustomCell.m

#import "AUCustomCell.h"

@implementation AUCustomCell

@synthesize descriptionLabel = _descriptionLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
      self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)]; 
      self.descriptionLabel.textColor = [UIColor blackColor]; 
      self.descriptionLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
      [self addSubview:self.descriptionLabel]; 
   } 

  return self;
}

@end

AUViewController.h

#import <UIKit/UIKit.h>

@interface AUViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

#import "AUViewController.h"
#import "AUCustomCell.h"

@interface AUViewController ()

@end

@implementation AUViewController { 
   UITableView *tableView;
}

- (void)viewDidLoad{ 
    [super viewDidLoad]; 

    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; 
    tableView.delegate = self;
    tableView.dataSource = self; 
    tableView.backgroundColor = [UIColor cyanColor];
   
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource

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

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{ 
  return 1;
}

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ 
   static NSString *cellIdentifier = @"AUCell";
   AUCustomCell *cell = (AUCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];

   if (cell == nil) { 
       cell = [[AUCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    } 

  cell.descriptionLabel.text = @"Testing"; 
  return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    NSLog(@"selected %d row", indexPath.row);
}


@end

上一篇下一篇

猜你喜欢

热点阅读