iPhone第二节:登录、通讯录界面
登录、通讯录界面
mainViewController.m
#import "ViewController.h"
#import "ViewController2.h"
#import "ViewController3.h"
#import "ViewControllerTest.h"@interface ViewController ()@end@implementation ViewController@synthesize textField, textField2;- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self;
}- (void)viewDidLoad
{[super viewDidLoad];//背景色self.view.backgroundColor = [UIColor blackColor];#pragma mark ==logoUIImageView * imageLogo = [[UIImageView alloc] initWithFrame:CGRectMake(89, 92, 143, 48)];imageLogo.image = [UIImage imageNamed:@"img_首页Logo.png"];[self.view addSubview:imageLogo];#pragma mark ==UserNametextField = [[UITextField alloc] initWithFrame:CGRectMake(45, 244, 230, 20)];//输入提示textField.placeholder = @"用户名";//编辑前出现的文本textField.text = @"HuaShan";textField.textColor = [UIColor whiteColor];textField.textAlignment = NSTextAlignmentLeft;textField.font = [UIFont systemFontOfSize:18.0];//清除按钮的模式textField.clearButtonMode = UITextFieldViewModeAlways;
#pragma mark ==输入提示//修改输入提示的颜色[textField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];//修改输入提示的颜色:方法二UIColor *color = [UIColor whiteColor];NSDictionary *dic = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"用户名" attributes:dic];textField.delegate = self;[self.view addSubview:textField];#pragma mark ==clearButton//替换UIButton * clearButton = [textField valueForKey:@"_clearButton"];[clearButton setBackgroundImage:[UIImage imageNamed:@"btn_首页用户名取消@2x.png"] forState:UIControlStateNormal];//新建UIButton * clearBtnSelf = [UIButton buttonWithType:UIButtonTypeCustom];clearBtnSelf.frame = CGRectMake(275, 244, 22, 22);clearBtnSelf.showsTouchWhenHighlighted = YES;[clearBtnSelf setBackgroundImage:[UIImage imageNamed:@"btn_首页用户名取消@2x.png"] forState:UIControlStateNormal];[clearBtnSelf addTarget:self action:@selector(clear) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:clearBtnSelf];#pragma mark ==lineUIImageView * imageLine = [[UIImageView alloc] initWithFrame:CGRectMake(45, 264, 230, 1)];imageLine.image = [UIImage imageNamed:@"img_首页输入框底线.png"];[self.view addSubview:imageLine];#pragma mark ==PassWordtextField2 = [[UITextField alloc] initWithFrame:CGRectMake(45, 291, 230, 20)];textField2.placeholder = @"密码";[textField2 setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];textField2.text = @"123456";textField2.textColor = [UIColor whiteColor];textField2.textAlignment = NSTextAlignmentLeft;textField2.font = [UIFont systemFontOfSize:18.0];textField2.clearButtonMode = UITextFieldViewModeAlways;//输入保护textField2.secureTextEntry = YES;textField2.delegate = self;[self.view addSubview:textField2];#pragma mark ==clearButton//替换UIButton * clearButton2 = [textField2 valueForKey:@"_clearButton"];[clearButton2 setBackgroundImage:[UIImage imageNamed:@"btn_首页用户名取消@2x.png"] forState:UIControlStateNormal];#pragma mark ==lineUIImageView * imageLine2 = [[UIImageView alloc] initWithFrame:CGRectMake(45, 311, 230, 1)];imageLine2.image = [UIImage imageNamed:@"img_首页输入框底线.png"];[self.view addSubview:imageLine2];#pragma mark ==loginButtonUIButton * btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];btnLogin.frame = CGRectMake(45, 325, 230, 45);btnLogin.showsTouchWhenHighlighted = YES;[btnLogin setBackgroundImage:[UIImage imageNamed:@"btn_登录_n.png"] forState:UIControlStateNormal];[btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btnLogin];#pragma mark ==logButtonUIButton * btnLogin2 = [UIButton buttonWithType:UIButtonTypeCustom];btnLogin2.frame = CGRectMake(45, 370, 230, 45);btnLogin2.showsTouchWhenHighlighted = YES;[btnLogin2 setBackgroundImage:[UIImage imageNamed:@"btn_注册_n.png"] forState:UIControlStateNormal];[btnLogin2 addTarget:self action:@selector(jump) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btnLogin2];#pragma mark ==contactButtonUIButton * btnLogin21 = [UIButton buttonWithType:UIButtonTypeCustom];btnLogin21.frame = CGRectMake(45, 415, 230, 45);btnLogin21.showsTouchWhenHighlighted = YES;[btnLogin21 setTitle:@"查看通讯录" forState:UIControlStateNormal];[btnLogin21 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];[btnLogin21 addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btnLogin21];
}
//清除方法
- (void)clear
{textField.text = nil;
}
//点击return的响应事件
- (BOOL)textFieldShouldReturn:(UITextField *)textfield
{[textfield resignFirstResponder];return YES;
}
//登录
- (void)login
{//判断输入的账号密码if ([textField.text isEqual: @"HuaShan"] && [textField2.text isEqualToString:@"123456"]){//登录提示UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"登录中,请稍候..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];[alert show];//1s后提示自动消失[self performSelector:@selector(dismiss:) withObject:alert afterDelay:1.0];//包含ViewController2.h并新建视图控制器ViewController2 * VC2 = [[ViewController2 alloc] init];//跳转方式VC2.modalTransitionStyle = 1;//跳转[self presentViewController:VC2 animated:YES completion:nil];}else{//错误提示UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"账号或密码错误,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];[alert show];}
}
//提示自动消失
- (void) dismiss:(UIAlertView *) Alert
{if (Alert){[Alert dismissWithClickedButtonIndex:[Alert cancelButtonIndex] animated:YES];}
}
//注册跳转
- (void)jump
{UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"注册中,请稍候..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];[alert show];[self performSelector:@selector(dismiss:) withObject:alert afterDelay:1.0];ViewController3 * VC3 = [[ViewController3 alloc] init];VC3.modalTransitionStyle = 2;[self presentViewController:VC3 animated:YES completion:nil];
}
//通讯录跳转
- (void)test
{ViewControllerTest * VCT = [[ViewControllerTest alloc] init];VCT.modalTransitionStyle = 2;[self presentViewController:VCT animated:YES completion:nil];
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}@endScrolViewController.m
#import "ViewController2.h"
//宏定义,屏幕宽、高
#define SCWIDTH self.view.frame.size.width
#define SCHEIGHT [[UIScreen mainScreen] bounds].size.height@interface ViewController2 ()@end@implementation ViewController2@synthesize labelTop;- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self;
}
//提示自动消失
- (void)dismiss:(UIAlertView *) alert
{if (alert){[alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];}
}- (void)viewDidLoad
{[super viewDidLoad];self.view.backgroundColor = [UIColor blackColor];//登录成功提示UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"登录成功,欢迎" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];[alert show];//1.5s自动消失[self performSelector:@selector(dismiss:) withObject:alert afterDelay:1.5];#pragma mark ==ScrollViewUIScrollView * SV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCWIDTH, SCHEIGHT)];//滚动条SV.showsHorizontalScrollIndicator = NO; //横向(水平滚动指示)SV.showsVerticalScrollIndicator = NO; //纵向(垂直滚动指示)//弹性SV.bounces = NO;//分页SV.pagingEnabled = YES;//添加图片为滚动视图的子视图for (int i = 0; i < 4; i++){UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, SCHEIGHT * i, SCWIDTH, SCHEIGHT)];imageV.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", i + 1]];[SV addSubview:imageV];}//滚动视图的尺寸扩展SV.contentSize = CGSizeMake(SCWIDTH, SCHEIGHT * 4);SV.delegate = self;[self.view addSubview:SV];#pragma mark ==labelTop//只显示一个label,改变其textlabelTop = [[UILabel alloc] initWithFrame:CGRectMake(120, 20, 80, 25)];//刚进入时显示的文本labelTop.text = [NSString stringWithFormat:@"当前页1/4"];labelTop.textAlignment = NSTextAlignmentCenter;labelTop.textColor = [UIColor whiteColor];labelTop.backgroundColor = [UIColor blackColor];labelTop.font = [UIFont systemFontOfSize:16.0];[self.view addSubview:labelTop];#pragma mark -buttonBackUIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];buttonBack.frame = CGRectMake(220, SCHEIGHT - 50 , 50, 30);[buttonBack setTitle:@"返回" forState:UIControlStateNormal];[buttonBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];//高亮变色[buttonBack setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];[buttonBack addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:buttonBack];
}- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{//分页模式,滑完,不分页模式滑到2分之1改变label.text(需点击)int currentPage = (scrollView.contentOffset.y - SCHEIGHT / 2) / SCHEIGHT + 1;//分页模式,滑完这一页改变label//int currentPage = scrollView.contentOffset.y / SCHEIGHT;labelTop.text =[NSString stringWithFormat:@"当前页%d/4", currentPage + 1 ];
}//- (void) scrollViewDidScroll:(UIScrollView *)scrollView
//{
// // 得到每页宽度 SCHEIGHT
//
// // 根据当前的y坐标和页高度计算出当前页数,滑到2分之1改变label
// int currentPage = (scrollView.contentOffset.y - SCHEIGHT / 2) / SCHEIGHT + 1;
// // 将当前页数赋给label
// labelTop.text =[NSString stringWithFormat:@"当前页%d/4", currentPage + 1];
//}//返回方法
- (void)back
{//当前视图控制器消失[self dismissViewControllerAnimated:YES completion:nil];
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}/*
#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.
}
*/@endlogViewController.m
#import "ViewController3.h"
#define SCWIDTH self.view.frame.size.width
#define SCHEIGHT [[UIScreen mainScreen] bounds].size.height@interface ViewController3 ()@end@implementation ViewController3@synthesize labelTop;- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self;
}- (void)viewDidLoad
{[super viewDidLoad];self.view.backgroundColor = [UIColor whiteColor];//注册提示UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"注册失败,请稍后重试" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];[alert show];#pragma mark ==scrollViewUIScrollView * SV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCWIDTH, SCHEIGHT)];SV.showsHorizontalScrollIndicator = NO;SV.pagingEnabled = NO;SV.bounces = NO;#pragma mark -addImage//先放图片UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCWIDTH, SCHEIGHT)];imageV.image = [UIImage imageNamed:[NSString stringWithFormat:@"2.jpg"]];[self.view addSubview:imageV];#pragma mark ==labelUILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(40, 50, 120, SCHEIGHT * 4)];label.text = @"注册失败! 服务器君去喝下午茶了,做道题等等它。 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?";label.numberOfLines = 0;label.textAlignment = NSTextAlignmentLeft;label.font = [UIFont systemFontOfSize:18.0];label.textColor = [UIColor redColor];[SV addSubview:label];SV.contentSize = CGSizeMake(SCWIDTH, SCHEIGHT * 4);SV.delegate = self;[self.view addSubview:SV];//label中不同的颜色显示//要显示的字符串stringNSString *string = @"注册过程中出现问题,致电400-650-5167";//颜色不同的字符串的范围rangeNSRange range = [string rangeOfString: @"400-650-5167"];//新建可变的属性化字符串,并用string初始化。(attribute,属性,特质)NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString: string];//为属性化字符串的特定范围添加属性[attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor redColor]} range: range];//新建labelUILabel *label2 = [[UILabel alloc] initWithFrame: CGRectMake(20, 50, 320, 50)];//设置label的文本为string,如果不写这句话,对于结果没有影响[label2 setText: string];//设置文本颜色为黑色label2.textColor = [UIColor blackColor];label2.font = [UIFont boldSystemFontOfSize:16];label2.numberOfLines = 0;//设置属性化文本,赋值为attribute[label2 setAttributedText: attribute];[self.view addSubview:label2];#pragma mark ==labelToplabelTop = [[UILabel alloc] initWithFrame:CGRectMake(120, 20, 80, 25)];labelTop.text = [NSString stringWithFormat:@"当前页1/4"];labelTop.backgroundColor = [UIColor blackColor];labelTop.font = [UIFont systemFontOfSize:16.0];labelTop.textAlignment = NSTextAlignmentCenter;labelTop.textColor = [UIColor whiteColor];[self.view addSubview:labelTop];#pragma mark -buttonBackUIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];buttonBack.frame = CGRectMake(220, SCHEIGHT - 50 , 50, 30);[buttonBack setTitle:@"返回" forState:UIControlStateNormal];[buttonBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];[buttonBack setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];[buttonBack addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:buttonBack];// Do any additional setup after loading the view.
}- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{//分页模式,滑完,不分页模式滑到滑到2分之1改变label(需点击)int currentPage = (scrollView.contentOffset.y - SCHEIGHT / 2) / SCHEIGHT + 1;//分页模式,滑完这一页改变label//int currentPage = scrollView.contentOffset.y / SCHEIGHT;labelTop.text =[NSString stringWithFormat:@"当前页%d/4", currentPage + 1 ];
}//- (void) scrollViewDidScroll:(UIScrollView *)scrollView
//{
// // 得到每页宽度 SCHEIGHT
//
// // 根据当前的y坐标和页高度计算出当前页数,滑到2分之1改变label
// int currentPage = (scrollView.contentOffset.y - SCHEIGHT / 2) / SCHEIGHT + 1;
// // 将当前页数赋给label
// labelTop.text =[NSString stringWithFormat:@"当前页%d/4", currentPage + 1];
//}- (void)back
{[self dismissViewControllerAnimated:YES completion:nil];
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}/*
#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.
}
*/@endContactViewController.m
//
// ViewControllerTest.m
// iPhoneNo827Class
//
// Created by zmm on 15/8/27.
// Copyright (c) 2015年 ___郑明明___. All rights reserved.
//#import "ViewControllerTest.h"
#import "Contact.h"
#import "ContactGroup.h"@interface ViewControllerTest () {UITableView * _tableView;NSMutableArray * _contacts;//联系人模型NSIndexPath * _selectedIndexPath;//当前选中的组和行UIToolbar * _toolbar;//工具栏BOOL _isInsert; //记录是点击了插入还是删除//BOOL _isSearching;UISearchBar * _searchBar;//搜索栏NSMutableArray * _searchContacts;//符合条件的搜索联系人UISearchDisplayController * _searchDisplayController;
}@end@implementation ViewControllerTest- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self;
}- (void)viewDidLoad
{[super viewDidLoad];//初始化数据[self initData];//分组样式的tableView_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];_tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0);[self.view addSubview:_tableView];#pragma mark ==editButtonUIButton * editButton = [UIButton buttonWithType:UIButtonTypeCustom];editButton.frame = CGRectMake(40, 20, 50, 20);editButton.showsTouchWhenHighlighted = YES;[editButton setTitle:@"编辑" forState:UIControlStateNormal];[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];[editButton addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:editButton];#pragma mark ==searchButtonUIButton * searchButton = [UIButton buttonWithType:UIButtonTypeCustom];searchButton.frame = CGRectMake(230, 20, 50, 20);searchButton.showsTouchWhenHighlighted = YES;[searchButton setTitle:@"搜索" forState:UIControlStateNormal];[searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];[searchButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:searchButton];//数据源,实现相应协议的方法_tableView.dataSource = self;//代理_tableView.delegate = self;_searchBar.delegate = self;_searchDisplayController.delegate = self;#pragma mark -buttonBackUIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];buttonBack.frame = CGRectMake(260, 420 , 50, 30);[buttonBack setTitle:@"返回" forState:UIControlStateNormal];[buttonBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];[buttonBack setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];[buttonBack addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:buttonBack];
}- (void)edit
{//添加工具栏[self addToolbar];_searchBar.hidden = YES;
}- (void)search
{//添加搜索栏[self addSearchBar];_toolbar.hidden = YES;
}- (void)back
{[self dismissViewControllerAnimated:YES completion:nil];
}#pragma mark ==加载数据
- (void)initData
{_contacts = [[NSMutableArray alloc] init];Contact * c1 = [Contact initWithFirstName:@"媳" andLastName:@"妇儿" andPhoneNumber:@"1314520"];ContactGroup * g1 = [ContactGroup initWithName:@"LO" andDetail:@"LOVER" andContacts:[NSMutableArray arrayWithObjects:c1, nil]];[_contacts addObject:g1];Contact * c2 = [Contact initWithFirstName:@"张" andLastName:@"三" andPhoneNumber:@"1101201"];Contact * c3 = [Contact initWithFirstName:@"张" andLastName:@"五" andPhoneNumber:@"1201191"];Contact * c4 = [Contact initWithFirstName:@"张" andLastName:@"七" andPhoneNumber:@"1141101"];ContactGroup * g2 = [ContactGroup initWithName:@"张" andDetail:@"姓张的朋友" andContacts:[NSMutableArray arrayWithObjects:c2, c3, c4, nil]];[_contacts addObject:g2];Contact * c5 = [Contact initWithFirstName:@"李" andLastName:@"二" andPhoneNumber:@"1234567"];Contact * c6 = [Contact initWithFirstName:@"李" andLastName:@"四" andPhoneNumber:@"2234567"];Contact * c7 = [Contact initWithFirstName:@"李" andLastName:@"六" andPhoneNumber:@"3234567"];Contact * c8 = [Contact initWithFirstName:@"李" andLastName:@"八" andPhoneNumber:@"4234567"];Contact * c9 = [Contact initWithFirstName:@"李" andLastName:@"十" andPhoneNumber:@"5234567"];ContactGroup * g3 = [ContactGroup initWithName:@"李" andDetail:@"姓李的朋友" andContacts:[NSMutableArray arrayWithObjects:c5, c6, c7, c8, c9, nil]];[_contacts addObject:g3];Contact * c10 = [Contact initWithFirstName:@"丁" andLastName:@"11" andPhoneNumber:@"1212121"];Contact * c11 = [Contact initWithFirstName:@"丁" andLastName:@"22" andPhoneNumber:@"1231231"];Contact * c12 = [Contact initWithFirstName:@"丁" andLastName:@"33" andPhoneNumber:@"1234123"];Contact * c13 = [Contact initWithFirstName:@"丁" andLastName:@"44" andPhoneNumber:@"1234512"];Contact * c14 = [Contact initWithFirstName:@"丁" andLastName:@"55" andPhoneNumber:@"1234567"];ContactGroup * g4 = [ContactGroup initWithName:@"丁" andDetail:@"姓丁的朋友" andContacts:[NSMutableArray arrayWithObjects:c10, c11, c12, c13, c14, nil]];[_contacts addObject:g4];}#pragma mark ==数据源方法
//返回分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{//NSLog(@"计算分组数");
// if (_isSearching)
// {
// return 1;
// }if (tableView == self.searchDisplayController.searchResultsTableView){return 1;}return _contacts.count;
}
//返回每组行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{//NSLog(@"计算每组(%i)行数", section);
// if (_isSearching)
// {
// return _searchContacts.count;
// }if (tableView == self.searchDisplayController.searchResultsTableView){return _searchContacts.count;}ContactGroup * g1 = _contacts[section];return g1.contacts.count;
}//typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
// UITableViewCellStyleDefault, // 左侧显示textLabel(不显示detailTextLabel),imageView可选(显示在最左边)
// UITableViewCellStyleValue1, // 左侧显示textLabel、右侧显示detailTextLabel(默认蓝色),imageView可选(显示在最左边)
// UITableViewCellStyleValue2, // 左侧依次显示textLabel(默认蓝色)和detailTextLabel,imageView可选(显示在最左边)
// UITableViewCellStyleSubtitle // 左上方显示textLabel,左下方显示detailTextLabel(默认灰色),imageView可选(显示在最左边)
//};
//typedef NS_ENUM(NSInteger, UITableViewCellAccessoryType) {
// UITableViewCellAccessoryNone, // 不显示任何图标
// UITableViewCellAccessoryDisclosureIndicator, // 跳转指示图标
// UITableViewCellAccessoryDetailDisclosureButton, // 内容详情图标和跳转指示图标
// UITableViewCellAccessoryCheckmark, // 勾选图标
// UITableViewCellAccessoryDetailButton NS_ENUM_AVAILABLE_IOS(7_0) // 内容详情图标
//};
//返回每行单元格
//生成单元格的方法并不是一次全部调用,而是只会生产当前显示在界面上的单元格,当用户滚动操作时再显示其他单元格。
//iOS中默认情况下不能定位到错误代码行,我们可以通过如下设置让程序定位到出错代码行:Show the Breakpoint navigator—Add Exception breakpoint。
//方法调用很频繁,无论是初始化、上下滚动、刷新都会调用此方法,所有在这里执行的操作一定要注意性能;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//工具栏隐藏//_toolbar.hidden= YES;//NSIndexPath是一个??,记录了组和行信息//NSLog(@"生成单元格(组:%i,行%i)", indexPath.section, indexPath.row);Contact * contact = nil;
// if (_isSearching)
// {
// contact = _searchContacts[indexPath.row];
// }if (tableView == self.searchDisplayController.searchResultsTableView){contact = _searchContacts[indexPath.row];}else{ContactGroup *group = _contacts[indexPath.section];contact = group.contacts[indexPath.row];}//UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil]; //原方法,不用缓存池//可重用标识可以有多个,如果在UITableView中有多类结构不同的Cell,可以通过这个标识进行缓存和新建//此方法调用非常频繁,cell的标识声明成静态变量有利于性能优化
// static NSString * cellId = @"UITableViewCellIdentifierKey1";
// //每组第一行增加switch
// static NSString * cellIdForRow = @"UITableViewCellIdentifierKeyWithSwitch";
// //首先根据标识去缓存池取
// UITableViewCell * cell ;
// if (indexPath.row == 0) //如果是第一行
// {
// cell = [tableView dequeueReusableCellWithIdentifier:cellIdForRow];
// }
// else
// {
// cell = [tableView dequeueReusableCellWithIdentifier:cellId];
// }
// //如果缓存池没有则新建并放到缓存池
// if (!cell)
// {
// if (indexPath.row == 0)
// {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdForRow];
// //新建switch
// UISwitch * sw = [[UISwitch alloc] init];
// //为sw添加响应事件
// [sw addTarget:self action:@selector(switchValueChange:) forControlEvents:UIControlEventValueChanged];
// //第一行,view定制右边显示的view(sw)
// cell.accessoryView = sw;
// }
// else
// {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
// //其他的,type指定cell右边显示的内容
// cell.accessoryType = UITableViewCellAccessoryDetailButton;
// }
// }
// if (indexPath.row == 0)
// {
// ((UISwitch *) cell.accessoryView).tag = indexPath.section;
// }static NSString * cellId = @"UITableViewCellIdentifierKey1";UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];if (!cell){cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];}cell.textLabel.text = [contact getName];cell.detailTextLabel.text = contact.phoneNumber;return cell;
}//返回每组头标题名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{//NSLog(@"生成组(组%i)名称",section);if (tableView==self.searchDisplayController.searchResultsTableView){return @"搜索结果";}ContactGroup *group=_contacts[section];return group.name;
}//返回每组尾部说明
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{//NSLog(@"生成尾部(组%i)详情",section);ContactGroup *group=_contacts[section];return [NSString stringWithFormat:@"分组详情:%@", group.detail];
}
//返回每组标题索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{NSLog(@"生成组索引");NSMutableArray * indexs = [[NSMutableArray alloc] init];for (ContactGroup * g in _contacts){[indexs addObject:g.name];}return indexs;
}
#pragma mark - 代理方法
//每行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{return 35;
}
//分组标题高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{if (section == 0){return 40;}return 30;
}
//分组详情高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{return 25;
}
//点击行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{_selectedIndexPath = indexPath;ContactGroup * g1 = _contacts[indexPath.section];Contact * c1 = g1.contacts[indexPath.row];//创建弹出窗口UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"修改信息" message:[c1 getName] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];//设置窗口内容样式alert.alertViewStyle = UIAlertViewStylePlainTextInput;//取得文本框UITextField * textField = [alert textFieldAtIndex:0];//设置文本框内容textField.text = c1.phoneNumber;[alert show];
}
//窗口代理方法,用户保存数据
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{if (buttonIndex == 1) //当点击第二个按钮(确定){UITextField * textField = [alertView textFieldAtIndex:0];//修改模型数据ContactGroup * group = _contacts[_selectedIndexPath.section];Contact * c = group.contacts[_selectedIndexPath.row];c.phoneNumber = textField.text;//[_tableView reloadData]; //刷新整个view//刷新表格NSArray *indexPaths = @[_selectedIndexPath];//需要局部刷新的单元格的组、行[_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//后面的参数代表更新时的动画}
}
//重写状态样式方法
- (UIStatusBarStyle)preferredStatusBarStyle
{return UIStatusBarStyleLightContent;
}
//开关切换的事件
- (void)switchValueChange:(UISwitch *)sw
{NSLog(@"section:%i, switch:%i", sw.tag, sw.on);
}#pragma mark ==添加工具栏
- (void)addToolbar
{//新建工具栏,指定位置和大小_toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];//设置背景颜色(没效果)_toolbar.backgroundColor = [UIColor blackColor];[self.view addSubview:_toolbar];//新建工具栏项目按钮,并添加对应方法UIBarButtonItem *removeButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)];UIBarButtonItem *flexibleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];//创建按钮数组,赋值给工具栏项目NSArray * buttonArray = [NSArray arrayWithObjects:removeButton, flexibleButton, addButton, nil];_toolbar.items = buttonArray;}- (void)remove
{//设置非插入、非编辑状态_isInsert = NO;[_tableView setEditing:!_tableView.isEditing animated:YES];
}- (void)add
{_isInsert = YES;[_tableView setEditing:!_tableView.isEditing animated:YES];
}#pragma mark ==编辑操作
//向左滑动就会显示删除按钮 ??
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ContactGroup * group = _contacts[indexPath.section];Contact * contact = group.contacts[indexPath.row];if (editingStyle == UITableViewCellEditingStyleDelete){[group.contacts removeObject:contact];//局部刷新[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];//如果分组没有数据,则删除分组if (group.contacts.count == 0){[_contacts removeObject:group];[tableView reloadData];}}else if (editingStyle == UITableViewCellEditingStyleInsert){Contact * contact2 = [[Contact alloc] init];contact2.firstName = @"FFF";contact2.lastName = @"LLL";contact2.phoneNumber = @"1234567890";[group.contacts insertObject:contact2 atIndex:indexPath.row];[tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];}
}//实现这个方法在编辑状态右侧就有排序图标
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{ContactGroup *sourceGroup = _contacts[sourceIndexPath.section];Contact *sourceContact = sourceGroup.contacts[sourceIndexPath.row];ContactGroup *destinationGroup = _contacts[destinationIndexPath.section];//删除源分组的源联系人[sourceGroup.contacts removeObject:sourceContact];//在目的分组的目的行插入源联系人[destinationGroup.contacts insertObject:sourceContact atIndex:destinationIndexPath.row];//如果源分组没有数据,则删除分组if(sourceGroup.contacts.count == 0){[_contacts removeObject:sourceGroup];[tableView reloadData];}
}//取得当前操作状态,根据不同的状态左侧出现不同的操作按钮
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{if (_isInsert){return UITableViewCellEditingStyleInsert;}elsereturn UITableViewCellEditingStyleDelete;
}#pragma mark ==搜索
//-(void)addSearchBar{
// CGRect searchBarRect=CGRectMake(0, 0, self.view.frame.size.width, 44);
// _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect];
// _searchBar.placeholder=@"Please input key word...";
// //_searchBar.keyboardType=UIKeyboardTypeAlphabet;//键盘类型
// //_searchBar.autocorrectionType=UITextAutocorrectionTypeNo;//自动纠错类型
// //_searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;//哪一次shitf被自动按下
// _searchBar.showsCancelButton = YES;//显示取消按钮
// //添加搜索框到页眉位置
// _searchBar.delegate=self;
// self->_tableView.tableHeaderView = _searchBar;
//}
-(void)addSearchBar{_searchBar=[[UISearchBar alloc]init];[_searchBar sizeToFit];//大小自适应容器_searchBar.placeholder=@"Please input key word...";_searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;_searchBar.showsCancelButton=YES;//显示取消按钮//添加搜索框到页眉位置_searchBar.delegate=self;self->_tableView.tableHeaderView=_searchBar;_searchDisplayController=[[UISearchDisplayController alloc]initWithSearchBar:_searchBar contentsController:self];_searchDisplayController.delegate=self;_searchDisplayController.searchResultsDataSource=self;_searchDisplayController.searchResultsDelegate=self;[_searchDisplayController setActive:NO animated:YES];}//选中之前
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{[_searchBar resignFirstResponder];//退出键盘return indexPath;
}#pragma mark ==搜索框代理
取消搜索
//-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
//{
// _isSearching=NO;
// _searchBar.text=@"";
// [self->_tableView reloadData];
//}
//
输入搜索关键字
//-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// if([_searchBar.text isEqual:@""])
// {
// _isSearching = NO;
// [self->_tableView reloadData];
// return;
// }
// [self searchDataWithKeyWord:_searchBar.text];
//}
//
点击虚拟键盘上的搜索时
//-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
//
// [self searchDataWithKeyWord:_searchBar.text];
//
// [_searchBar resignFirstResponder];//放弃第一响应者对象,关闭虚拟键盘
//}
//
//#pragma mark 搜索形成新数据
//-(void)searchDataWithKeyWord:(NSString *)keyWord{
// _isSearching = YES;
// _searchContacts = [NSMutableArray array];
// [_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
// {
// ContactGroup *group = obj;
// [group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
// {
// Contact *contact = obj;
// if ([contact.firstName.uppercaseString rangeOfString:keyWord.uppercaseString].length||[contact.lastName.uppercaseString rangeOfString:keyWord.uppercaseString].length||[contact.phoneNumber.uppercaseString rangeOfString:keyWord.uppercaseString].length)
// {
// [_searchContacts addObject:contact];
// }
// }];
// }];
//
// //刷新表格
// [self->_tableView reloadData];
//}//UISearchDisplayController代理方法
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{[self searchDataWithKeyWord:searchString];return YES;
}#pragma mark 搜索形成新数据
-(void)searchDataWithKeyWord:(NSString *)keyWord{_searchContacts = [NSMutableArray array];[_contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){ContactGroup *group = obj;[group.contacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){Contact *contact = obj;if ([contact.firstName.uppercaseString rangeOfString:keyWord.uppercaseString].length||[contact.lastName.uppercaseString rangeOfString:keyWord.uppercaseString].length||[contact.phoneNumber.uppercaseString rangeOfString:keyWord.uppercaseString].length){[_searchContacts addObject:contact];}}];}];
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}/*
#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.
}
*/@end Contact
#import @interface Contact : NSObject#pragma mark 姓
@property (nonatomic,copy) NSString *firstName;
#pragma mark 名
@property (nonatomic,copy) NSString *lastName;
#pragma mark 手机号码
@property (nonatomic,copy) NSString *phoneNumber;-(Contact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber;-(NSString *)getName;+(Contact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber;@end
#import "Contact.h"@implementation Contact- (Contact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber
{if(self=[super init]){self.firstName = firstName;self.lastName = lastName;self.phoneNumber = phoneNumber;}return self;
}- (NSString *)getName
{return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
}+(Contact *)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName andPhoneNumber:(NSString *)phoneNumber
{Contact *contact1 = [[Contact alloc] initWithFirstName:firstName andLastName:lastName andPhoneNumber:phoneNumber];return contact1;
}@end ContactGroup
#import @interface ContactGroup : NSObject#pragma mark 组名
@property (nonatomic,copy) NSString *name;#pragma mark 分组描述
@property (nonatomic,copy) NSString *detail;#pragma mark 联系人
@property (nonatomic,strong) NSMutableArray *contacts;-(ContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts;+(ContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts;@end
#import "ContactGroup.h"@implementation ContactGroup-(ContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts
{if (self = [super init]){self.name = name;self.detail = detail;self.contacts = contacts;}return self;
}+(ContactGroup *)initWithName:(NSString *)name andDetail:(NSString *)detail andContacts:(NSMutableArray *)contacts
{ContactGroup *group1=[[ContactGroup alloc] initWithName:name andDetail:detail andContacts:contacts];return group1;
}@end
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
