国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS App開發中使用及自定義UITableViewCell的教程

2019-10-21 18:54:36
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了iOS App開發中使用及自定義UITableViewCell的教程,自定義TableViewCell文中使用Objective-C演示而非ib,需要的朋友可以參考下
 

UITableView用來以表格的形式顯示數據。關于UITableView,我們應該注意:

(1)UITableView用來顯示表格的可見部分,UITableViewCell用來顯示表格的一行。

(2)UITableView并不負責存儲表格中的數據,而是僅僅存儲足夠的數據使得可以畫出當前可見部分。

(3)UITableView從UITableViewDelegate協議獲取配置信息,從UITableViewDataSource協議獲得數據信息。

(4)所有的UITableView實現時實際上只有一列,但是我們可以通過向UITableViewCell中添加子視圖,使得它看起來有好幾列。

(5)UITableView有兩種風格:

    ① Grouped:每一組看起來像是圓矩形;
    ② Plain:這是默認風格,可以修改成Indexed風格。
    
UITableViewCell使用實例
在下邊的小例子中,我們將先實現顯示一列數據,然后在每行添加圖像,之后再看看UITableViewCell的四種分別是什么樣的。最后再進行其他操作,比如設置縮進、修改字體大小和行高等。

1、運行Xcode 4.2,新建一個Single View Application,名稱為Table Sample:

iOS,App開發,UITableViewCell

2、單擊ViewController.xib,使用Interface Builder給視圖添加一個UITableView控件,并使其覆蓋整個視圖:

iOS,App開發,UITableViewCell

3、選中新添加的UITableView控件,打開Connection Inspector,找到delegate和datasource,從它們右邊的圓圈拉線到File's Owner圖標:

iOS,App開發,UITableViewCell

4、單擊ViewController.h,在其中添加代碼:

復制代碼代碼如下:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) NSArray *listData;
@end

5、單擊ViewController.m,在其中添加代碼:

 

5.1 在@implementation后面添加代碼:

復制代碼代碼如下:

@synthesize listData;

5.2 在viewDidLoad方法中添加代碼:
復制代碼代碼如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSArray *array = [[NSArray alloc] initWithObjects:@"Tree", @"Flower",
                      @"Grass", @"Fence", @"House", @"Table", @"Chair",
                      @"Book", @"Swing" , nil]; 
    self.listData = array; 
}

5.3 在viewDidUnload方法中添加代碼:
復制代碼代碼如下:

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.listData = nil;
}

5.4 在@end之前添加代碼:
復制代碼代碼如下:

#pragma mark - 
#pragma mark Table View Data Source Methods 
//返回行數
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section { 
    return [self.listData count]; 
}

 

//新建某一行并返回
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier"; 
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
                             TableSampleIdentifier]; 
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleDefault 
                reuseIdentifier:TableSampleIdentifier]; 
    } 
    
    NSUInteger row = [indexPath row]; 
    cell.textLabel.text = [listData objectAtIndex:row]; 
 return cell; 
}


上面的第二個方法中,
復制代碼代碼如下:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];

這個語句根據標識符TableSampleIdentifier尋找當前可以重用的UITableViewCell。當某行滑出當前可見區域后,我們重用它所對應的UITableViewCell對象,那么就可以節省內存和時間。
如果執行詞語后,cell為nil,那我們再創建一個,并設置去標識符為TableSampleIdentifier:
復制代碼代碼如下:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];

這里UITableViewCellStyleDefault是表示UITableViewCell風格的常數,除此之外,還有其他風格,后面將會用到。
注意參數(NSIndexPath *)indexPath,它將行號row和部分號section合并了,通過[indexPath row];獲取行號。之后給cell設置其文本:
復制代碼代碼如下:

cell.textLabel.text = [listData objectAtIndex: row];

6、運行一下:

 

iOS,App開發,UITableViewCell

7、給每一行添加圖片:
7.1 將圖片資源添加到工程:拖到工程中,前面的文章有提到。
7.2 在cellForRowAtIndexPath方法的return語句之前添加代碼:

復制代碼代碼如下:

UIImage *image = [UIImage imageNamed:@"blue.png"]; 
cell.imageView.image = image; 
UIImage *highLighedImage = [UIImage imageNamed:@"yellow.png"]; 
cell.imageView.highlighedImage = highLighedImage;

7.3 運行,效果如下:

 

iOS,App開發,UITableViewCell

可以看到,每行左邊都出現一張圖片。當選中某行,其圖片改變。

8、設置行的風格:
表示UITableViewCell風格的常量有:

復制代碼代碼如下:

UITableViewCellStyleDefault
UITableViewCellStyleSubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2

這幾種風格的區別主要體現在Image、Text Label以及Detail Text Label。
為了體現風格,在cellForRowAtIndexPath方法的return語句之前添加代碼:
復制代碼代碼如下:

cell.detailTextLabel.text = @"Detail Text";

然后將
復制代碼代碼如下:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];

中的UITableViewCellStyleDefault依次換成上面提到的四個風格常量,并運行,效果分別如下:

 

iOS,App開發,UITableViewCell

UITableViewCellStyleDefault   

iOS,App開發,UITableViewCell

UITableViewCellStyleSubtitle

iOS,App開發,UITableViewCell

UITableViewCellStyleValue1 

iOS,App開發,UITableViewCell

UITableViewCellStyleValue2 
     
9、設置縮進:

將所有行的風格改回UITableViewCellStyleDefault,然后在@end之前添加代碼如下:

復制代碼代碼如下:

#pragma mark Table Delegate Methods 
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger row = [indexPath row]; 
    return row; 
}

這里將第row行縮進row,如下圖所示:

 

iOS,App開發,UITableViewCell

10、操縱行選擇:
在@end之前添加代碼:

復制代碼代碼如下:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger row = [indexPath row];
    if (row%2 == 0) {
        return nil;
    }
    return indexPath; 
}

上面的方法在選擇某行之前執行,我們可以在這個方法中添加我們想要的操作。這里,我們實現的是,如果選擇的行號(從0開始計)是偶數,則取消選擇。
在@end之前添加代碼:
復制代碼代碼如下:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSUInteger row = [indexPath row]; 
    NSString *rowValue = [listData objectAtIndex:row]; 
    
    NSString *message = [[NSString alloc] initWithFormat: 
                         @"You selected %@", rowValue]; 
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle:@"Row Selected!" 
                          message:message 
                          delegate:nil 
                          cancelButtonTitle:@"Yes I Did" 
                          otherButtonTitles:nil]; 
    [alert show]; 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
}

當選擇某行之后,就彈出一個Alert,用來顯示我們所做的選擇。
運行一下,你會發現第0、2等行無法選擇。選擇奇數行時會彈出提示:

 

iOS,App開發,UITableViewCell

而且關閉提示框后,選擇的那行也被取消了選擇,用的語句

復制代碼代碼如下:

[tableView deselectRowAtIndexPath:indexPath animated:YES];

11、設置字體大小和表格行高:
11.1 在cellForRowAtIndexPath方法中的return之前添加代碼,用于設置字體和大小:
復制代碼代碼如下:

cell.textLabel.font = [UIFont boldSystemFontOfSize:50];

11.2 在@end之前添加代碼,用于設置行高:
復制代碼代碼如下:

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

運行,看看效果:

 

iOS,App開發,UITableViewCell

 

可任意自定義的UITableViewCell
UITableView的強大更多程度上來自于可以任意自定義UITableViewCell單元格。通常,UITableView中的Cell是動態的,在使用過程中,會創建一個Cell池,根據每個cell的高度(即tableView:heightForRowAtIndexPath:返回值),以及屏幕高度計算屏幕中可顯示幾個cell。而進行自定義TableViewCell無非是采用代碼實現或采用IB編輯nib文件來實現兩種方式,本文主要收集代碼的方式實現各種cell自定義。
1.如何動態調整Cell高度

復制代碼代碼如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.tag = 1;
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.highlightedTextColor = [UIColor whiteColor];
        label.numberOfLines = 0;
        label.opaque = NO; // 選中Opaque表示視圖后面的任何內容都不應該繪制
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
    }
 
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    NSString *text;
    text = [textArray objectAtIndex:indexPath.row];
    CGRect cellFrame = [cell frame];
    cellFrame.origin = CGPointMake(0, 0);
 
    label.text = text;
    CGRect rect = CGRectInset(cellFrame, 2, 2);
    label.frame = rect;
    [label sizeToFit];
    if (label.frame.size.height > 46) {
        cellFrame.size.height = 50 + label.frame.size.height - 46;
    }
    else {
        cellFrame.size.height = 50;
    }
    [cell setFrame:cellFrame];
 
    return cell;
}

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}


2.如何用圖片自定義Table Separeator分割線
一般地,利用類似[tableView setSeparatorColor:[UIColor redColor]];語句即可修改cell中間分割線的顏色。那又如何用一個圖片作為分割線背景呢?可以嘗試如下:
方法一:
先設置cell separatorColor為clear,然后把圖片做的分割線添加到自定義的custom cell上。

 

方法二:
在cell里添加一個像素的imageView后將圖片載入進,之后設置tableView.separatorStyle = UITableViewCellSeparatorStyleNone

3.自定義首行Cell與其上面導航欄間距

復制代碼代碼如下:

tableView.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,5,20)] autorelease];

4.自定義UITableViewCell的accessory樣式
默認的accessoryType屬性有四種取值:UITableViewCellAccessoryNone、UITableViewCellAccessoryDisclosureIndicator、UITableViewCellAccessoryDetailDisclosureButton、UITableViewCellAccessoryCheckmark。如果想使用自定義附件按鈕的其他樣式,則需使用UITableView的accessoryView屬性來指定。
復制代碼代碼如下:

UIButton *button;
if(isEditableOrNot) {
    UIImage *image = [UIImage imageNamed:@"delete.png"];
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0,0.0,image.size.width,image.size.height);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
}else{
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
}

以上代碼僅僅是定義了附件按鈕兩種狀態下的樣式,問題是現在這個自定義附件按鈕的事件仍不可用。即事件還無法傳遞到UITableViewDelegate的accessoryButtonTappedForRowWithIndexPath方法上。當我們在上述代碼中在加入以下語句:
復制代碼代碼如下:
[button addTarget:self action:@selector(btnClicked:event:) forControlEvents:UIControlEventTouchUpInside];

后,雖然可以捕捉到每個附件按鈕的點擊事件,但我們還無法進行區別到底是哪一行的附件按鈕發生了點擊動作!因為addTarget:方法最多允許傳遞兩個參數:target和event,這兩個參數都有各自的用途了(target指向事件委托對象,event指向所發生的事件)。看來只依靠Cocoa框架已經無法做到了。

 

      但我們還是可以利用event參數,在自定義的btnClicked方法中判斷出事件發生在UITableView的哪一個cell上。因為UITableView有一個很關鍵的方法indexPathForRowAtPoint,可以根據觸摸發生的位置,返回觸摸發生在哪一個cell的indexPath。而且通過event對象,正好也可以獲得每個觸摸在視圖中的位置。

復制代碼代碼如下:

// 檢查用戶點擊按鈕時的位置,并轉發事件到對應的accessory tapped事件
- (void)btnClicked:(id)sender event:(id)event
{
     NSSet *touches = [event allTouches];
     UITouch *touch = [touches anyObject];
     CGPoint currentTouchPosition = [touch locationInView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
     if(indexPath != nil)
     {
         [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
     }
}

這樣,UITableView的accessoryButtonTappedForRowWithIndexPath方法會被觸發,并且獲得一個indexPath參數。通過這個indexPath參數,我們即可區分到底哪一行的附件按鈕發生了觸摸事件。
復制代碼代碼如下:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    int  *idx = indexPath.row;
   //這里加入自己的邏輯
}


注:相關教程知識閱讀請移步到IOS開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄浦区| 左权县| 巴南区| 闻喜县| 鄱阳县| 尚志市| 三原县| 舞阳县| 称多县| 和林格尔县| 全南县| 禹城市| 上杭县| 大田县| 平阳县| 淮南市| 新平| 天峨县| 庐江县| 布尔津县| 巧家县| 元氏县| 公安县| 广东省| 杂多县| 鄂尔多斯市| 林周县| 霍州市| 西安市| 遵义县| 元朗区| 麻阳| 桂平市| 彭泽县| 安平县| 黔西| 吴忠市| 邯郸市| 乌恰县| 昌江| 连平县|