UITableView(一)创建表示图并且添加数据

来源:互联网 发布:php参考书籍 编辑:程序博客网 时间:2024/05/18 03:35

创建表示图(开发环境Xcode5.0.2)

(1)创建一个空的工程

(2)创建一个类,继承UIViewController,定义数组,和表示图

UIViewController.h文件

代码如下

#import <UIKit/UIKit.h>

 

@interface ViewController :UIViewController<UITableViewDataSource,UITableViewDelegate>

 

@property(nonatomic,retain)NSArray*listdata;//表示图的内容

@property(nonatomic,retain)UITableView*tableview;

@end

(3)ViewController.h导入到AppDelegate.m文件中,并且在

-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加以下代码

//表示图上面加个导航栏

ViewController* rootview=[[ViewControlleralloc]init];

   UINavigationController*nag=[[UINavigationControlleralloc]initWithRootViewController:rootview];

   self.window.rootViewController=nag;

(3)UIViewController.m文件

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

   if (self) {

       // Custom initialization

       self.title=@"联系人";//导航栏的标题

    }

   return self;

}

 

 

- (void)viewDidLoad

{

   [super viewDidLoad];

               UITableView*table=[[UITableViewalloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];

   table.backgroundColor=[UIColor yellowColor];

   table.dataSource=self;//代理模式

   table.delegate=self;//数据源代理模式

   _listdata=[[NSArray alloc]init];

   _listdata=@[@"老师",@"同学",@"朋友",@"室友",@"亲人",@"其他"];

   [self.view addSubview:table];

   

}

 

- (void)didReceiveMemoryWarning

{

   [super didReceiveMemoryWarning];

    //Dispose of any resources that can be recreated.

}

#pragma mark - Table view data source

//返回几个组sectionUITableViewStylePlain样式,只有一组

-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView

{

   return 1;

}

//返回数组里面的数据个数

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

{

   return _listdata.count;

}

//给单元格中添加数据

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

{

   UITableViewCell* cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:Nil];

   NSString* text=nil;

   text=_listdata[indexPath.row];

   cell.textLabel.text=text;

       //标记的样式,总共有四种

   cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

               //选中以后的状态,总共有3

   cell.selectionStyle=UITableViewCellSelectionStyleBlue;

   return cell;

}

0 0
原创粉丝点击