ios:TableView的用法


通過兩種方法來實現: 

一、通過動態數組NSMutableArray中的數據,來顯示數據

 

1.新建Empty Application項目,新建ViewController,HomeViewController,在AppDelegate.m中導入該文件,

並在方法- (BOOL)application:didFinishLaunchingWithOptions:中添加以下紅色標記的代碼

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    HomeViewController *homeViewController = [[HomeViewController alloc] init];
    self.window.rootViewController = homeViewController;
    [homeViewController release];
    
    [self.window makeKeyAndVisible];
    return YES;

 

2.在 HomeViewController.xib上添加Table View控件

將其Outlets的dataSource和delegate與File's Owner建立關聯,

 目的:(1) dataSource: 向HomeViewController添加UITableViewDataSource協議,從而可以在該類中使用相關的協議方法,在Table View中顯示數據。 

         (2) delegate :向HomeViewController添加UITableViewDelegate協議,從而可以在該類中使用相關的協議方法,響應用戶在Table View中的交互操作。

 

 在HomeViewController.h中添加協議

#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>{
}
@end

目的:都添加協議,有備無患。提高代碼編寫的效率和可靠性。

 

3. 在HomeViewController.m中編寫代碼

 

#import "HomeViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
NSMutableArray *listOfContacts;//聲明動態數組
- (void)viewDidLoad
{
 
    listOfContacts = [[NSMutableArray alloc] init];//分配內存並初始化
    
    [listOfContacts addObject:@"張三"];
    [listOfContacts addObject:@"張1"];
    [listOfContacts addObject:@"張2"];
    [listOfContacts addObject:@"張3"];
    [listOfContacts addObject:@"張4"];
    [listOfContacts addObject:@"張5"];
    [listOfContacts addObject:@"張6"];
    [listOfContacts addObject:@"張7"];
    [listOfContacts addObject:@"張8"];
    [listOfContacts addObject:@"張9"];
    [listOfContacts addObject:@"張11"];
    [listOfContacts addObject:@"張12"];
    [listOfContacts addObject:@"張13"];
    [listOfContacts addObject:@"張14"];
    [listOfContacts addObject:@"張15"];
    [listOfContacts addObject:@"張16"];
    [listOfContacts addObject:@"張17"];
    [listOfContacts addObject:@"張18"];
    [listOfContacts addObject:@"張19"];
    
    [super viewDidLoad];
}
//使用 UITableViewDataSource協議的tableView:cellForRowAtIndexPath:方法
//該方法 用來將數據填充進Table View的單元格中
/*
 在Table View中每填充一個單元格的數據就會觸發一次該事件。
 注意:如果我們的數據一共有200項,並不代表會連續觸發200次這個事件,如果當前屏幕只能顯示10行數據的話,就只會觸發10次該事件,當用戶滾動該Table View而產生新的單元格時,才會繼續觸發該事件。
 */
- ( UITableViewCell *) tableView :(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIndentifier = @"Contact";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    /*
     dequeueReusableCellWithIdentifier方法,獲取UITableViewCell類型的對象,而且獲取的是一個已經在TableView中使用過並可以復用的對象。
     想象一下:
     如果數組中有1000個元素,我們為每一個元素都實例化一個UITableViewCell對象的話,系統就會內存溢出甚至崩潰。其實每個用戶在一個屏幕中能夠看到的單元格數量也就十幾個,他們通過上下滾動屏幕的操作可以讓一些已顯示的單元格消除,而這些單元格對象系統就會保留下來以備我們需要顯示新單元格時可以復用它們,從而達到了節省系統資源的目的。這個方法包含一個參數CellIdentifier, 它用於指明你需要哪個標識的可復用單元格。在同一界面中如果有多個表格的情況時非常有用。
     當然如果沒有獲取到可復用的單元格時,我們就需要使用UITableViewCell的initWithStyle:reuseIdentifier:方法直接實例化一個單元格。其中reuseIdentifier參數用於設置該表格的可復用標識。
     */
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier] autorelease];
        
    }
    
    NSString *cellValue = [listOfContacts objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;
    

    //示意標志: Disclosure Indicator,Disclosure Button,Checkmark,默認為None

    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    //cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    //cell.accessoryType = UITableViewCellAccessoryCheckmark;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    //單元格添加圖片
    UIImage *image = [UIImage imageNamed:@"avatar.png"];
    cell.imageView.image = image;
    
    return cell;
}
//使用 UITableViewDataSource協議的tableView:numberOfRowsInSection:方法
//該方法用來設置 Table View中要顯示數據的行數
- ( NSInteger) tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [listOfContacts count];
}
//添加標題和腳本信息
- ( NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

      return @"聯系人列表";

    
}
- ( NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"作者:what if";
}
 

 

 

 / /UITableViewDelegate協議的方法, 選擇表格中的項目
- ( void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *contactSelected = [listOfContacts objectAtIndex:[indexPath row]];
    NSString *msg = [[NSString alloc] initWithFormat:@"您選擇的聯系人:%@", contactSelected];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"選擇聯系人" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    [contactSelected release];
    [msg release];
 // UITableViewDelegate協議的方法, 表格中的縮進
- ( NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath :(NSIndexPath *)indexPath{
    return [indexPath row] % 9;
    
}
- (void)dealloc{

 

    [listOfContacts release];
    [super dealloc];
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

 

二、通過plist文件提供數據,來顯示數據,方便分組

 1.添加contacts.plist文件

 2. 

HomeViewController.h中添加代碼

#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>{
}
@property (nonatomic, retain) NSDictionary *contactTitles;//存儲所有的聯系人信息
@property (nonatomic, retain) NSArray *groups;//所有分類名稱存入數組中

@end 

 

3HomeViewController.m中添加代碼


#import "HomeViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
@synthesize contactTitles;
@synthesize groups;
- (void)viewDidLoad
{
   
    NSString *path = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"plist"];//plist文件路徑
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.contactTitles = dict;
    [dict release];
    
    NSArray *array = [[contactTitles allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    self.groups = array;
    [super viewDidLoad];
}
//使用UITableViewDataSource協議的tableView:cellForRowAtIndexPath:方法
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIndentifier = @"Contact";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier] autorelease];
        
    }
    
    
       NSString *group = [groups objectAtIndex:[indexPath section]];
NSArray * contactSection = [contactTitles objectForKey:group];
cell.textLabel.text = [contactSection objectAtIndex:[indexPath row]];
    
    //單元格添加圖片
    UIImage *image = [UIImage imageNamed:@"avatar.png"];
    cell.imageView.image = image;
    
    
    return cell;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return [groups count];
}
//使用UITableViewDataSource協議的tableView:numberOfRowsInSection:方法
//該方法用來設置Table View中要顯示數據的行數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
    NSString *group = [groups objectAtIndex:section];
    NSArray *contactSection = [contactTitles objectForKey:group];
    
    return [contactSection count];
}
//添加標題和腳本信息
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *group = [groups objectAtIndex:section];
    return group;
    
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"作者:what if";
}


 

 

 /*//UITableViewDelegate協議的方法,選擇表格中的項目
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *contactSelected = [listOfContacts objectAtIndex:[indexPath row]];
    NSString *msg = [[NSString alloc] initWithFormat:@"您選擇的聯系人:%@", contactSelected];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"選擇聯系人" message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    [contactSelected release];
    [msg release];
} */
/*
 //UITableViewDelegate協議的方法,表格中的縮進
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [indexPath row] % 9;
    
}*/

//索引功能 

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return groups;
}
//用戶點擊標志后觸發的事件,只有DetailDisclosure Button才有該事件
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    //進入到該項目的詳細信息頁面

 

 

- (void)dealloc{
    
    [contactTitles release];
    [groups release];
    [super dealloc];
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

 

4.在xib文件中修改其Style為Grouped

 顯示效果:

 

 

 

 備注:

修改單元格的方法:

textLabel.font  使用UIFont設置單元格標簽的字體

textLabel.lineBreakMode   使用UILineBreakMode指定單元格標簽的文本如何換行

textLabel.text   將單元格標簽的內容設置為一個NSString

textLabel.textAlignment   使用UITextAlignment設置單元格標簽文本的對齊方式

textLabel.textColor    使用UIColor設置單元格標簽文本的顏色

textLabel.selectedTextColor   使用UIColor設置選定文本的顏色

imageView.image   將單元格的圖像視圖設置為一個UIImage

imageView.selectedImage   將選定單元格的內容設置為UIImage

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM