iOS開發——純代碼界面(自定義UITableViewCell)

自定義UITableViewCell

創建一個TableViewController類繼承於UITableViewController,創建一個TableViewCell類繼承於UITableViewCell。

AppDelegate.m編寫代碼如下

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    TableViewController *view = [[TableViewController alloc] init];
    self.window.rootViewController = view;
    [self.window makeKeyAndVisible];
    return YES;
}

自定義Cell,在TableViewCell.m中編寫代碼如下

//cell自定義用的是-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        //這裏順便介紹小UIButton的創建
        //設置button的類型是UIButtonTypeRoundedRect
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        //設置button的frame
        button.frame = CGRectMake(20, 20, 50, 50);

        //button正常狀態title設置爲Yes,被選擇狀態title設置爲No
        [button setTitle:@"Yes" forState:UIControlStateNormal];
        [button setTitle:@"No" forState:UIControlStateSelected];

        //設置button響應點擊事件的方法是buttonPressed:
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        //添加到cell
        [self addSubview:button];

        //創建imageView添加到cell中
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Totoro副本"]];
        imageView.frame = CGRectMake(150, 20, 150, 100);
        [self addSubview:imageView];

    }
    return self;
}

//buttonPressed:方法
-(void)buttonPressed:(UIButton *)button
{
    //實現按鈕狀態的切換
    button.selected = !button.selected;
}

TableViewController.m中編寫如下代碼

//用來指定表視圖的分區個數
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    //分區設置爲1
    return 1;
}

//用來指定特定分區有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //設置爲20行
    return 20;
}

//配置特定行中的單元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {

        //單元格樣式設置爲UITableViewCellStyleDefault
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }    
    return cell;
}

//設置單元格的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat
{
    //這裏設置成150
    return 150;
}

運行代碼,結果如下圖所示
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章