iOS开发-委托实战

十度 IOS 2015年12月01日 收藏

昨天晚上头疼,写了一部分草草的收笔了,早上起来补发一篇文章,昨天关于委托的基本使用和概念都稍微讲了一下,最开始学习委托的时候苹果官网和中文的博客文章看了不少,相似指数比较高。委托在命名要准确,最好是一看名字就知道用法,看名字就知道是干什么用的,比如说UINavigationControllerDelegate,UITableViewDelegate,这样命名不管是自己开始还是别人维护都是一个非常省心的事情,一举两得。

页面布局

先来看下效果图,这样大概知道应该实现的内容,效果如下:

 

这种实现,在故事板中的布局就是一个NavigationController和一个UITableView的静态表格:

其实添加的按钮是控件库中的Bar Buttom Item,将其中的Identifier设置为Add就可以是上面的效果,有一点需要说明的,添加书籍的视图中是静态单元格,需要删除控制器中多余的方法,不然无法出现效果。

Demo实现

上面跟委托有关联的地方就是保存的时候需要将数据讲给主视图去新增,而不是自己新增数据,可以通过定义一个委托实现上面的效果,具体可以参考本人的上一篇文章。需要先定义一个Book类用来存储数据: 

  1. #import <Foundation/Foundation.h>
  2. #import <UIKit/UIKit.h>
  3.  
  4. @interface Book : NSObject<NSCoding>
  5.  
  6. @property (strong,nonatomic) UIImage *ConverPicture;
  7.  
  8. @property (strong,nonatomic) NSString *BookName;
  9.  
  10. @property (strong,nonatomic) NSString *Author;
  11.  
  12. @property (strong,nonatomic) NSNumber *Price;
  13.  
  14. @end

Book.m需要存储数据实现两个方法,具体参考之前的文章NSCoder存储数据:

  1. //
  2. // Book.m
  3. // MySearchBar
  4. //
  5. // Created by keso on 15/2/4.
  6. // Copyright (c) 2015年 keso. All rights reserved.
  7. //
  8.  
  9. #import "Book.h"
  10.  
  11. @implementation Book
  12.  
  13. - (void)encodeWithCoder:(NSCoder *)aCoder{
  14. //注意这里是存储的是JPG图片的调用
  15. [aCoder encodeObject:UIImageJPEGRepresentation(self.ConverPicture,1.0)forKey:@"ConverPicture"];
  16. [aCoder encodeObject:_BookName forKey:@"BookName"];
  17. [aCoder encodeObject:_Author forKey:@"Author"];
  18. [aCoder encodeObject:_Price forKey:@"Price"];
  19. }
  20.  
  21. - (id)initWithCoder:(NSCoder *)aDecoder{
  22. self.ConverPicture=[UIImage imageWithData:[aDecoder decodeObjectForKey:@"ConverPicture"]];
  23. self.BookName=[aDecoder decodeObjectForKey:@"BookName"];
  24. self.Author=[aDecoder decodeObjectForKey:@"Author"];
  25. self.Price=[aDecoder decodeObjectForKey:@"Price"];
  26. return self;
  27. }
  28. @end

  首先来看第一个视图:RootViewController.h中的声明:

  1. #import <UIKit/UIKit.h>
  2. #import "EditViewController.h"
  3.  
  4. @interface RootViewController : UITableViewController<CustomEditViewControllerDelegate>
  5.  
  6.  
  7. @end

 RootViewController.m中ViewDiLoad中方法加载数据:

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. NSArray *codepath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  4. self.BookPath= [codepath[0] stringByAppendingPathComponent:@"Book.plist"];
  5. //这个路径暂时好像还没有存储数据的说
  6. NSFileManager *fileManager = [NSFileManager defaultManager];
  7. self.BookList=[[NSMutableArray alloc]init];
  8. NSLog(@"%@",NSHomeDirectory());
  9. if([fileManager fileExistsAtPath:_BookPath]){
  10. self.BookList=[NSKeyedUnarchiver unarchiveObjectWithFile:self.BookPath];
  11. }
  12.  
  13.  
  14. }

实现UITableView中的方法:

  1. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  2.  
  3. return 1;
  4. }
  5.  
  6. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  7.  
  8. return [self.BookList count];
  9. }
  10.  
  11.  
  12. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  13. static NSString *cellflag = @"BookCellFlag";
  14. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellflag];
  15.  
  16. Book *book=self.BookList[indexPath.row];
  17. [cell.textLabel setText:book.BookName];
  18. [cell.detailTextLabel setText:book.Author];
  19. [cell.imageView setImage:book.ConverPicture];
  20. return cell;
  21. }
  22.  
  23. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
  24. if ([segue.identifier isEqualToString:@"editSegue"]) {
  25. EditViewController *controller = segue.destinationViewController;
  26. [controller setCustomDelegate:self];
  27. }
  28.  
  29. }

  prepareForSegue用来处理新增的动作,主视图生命了自定义的委托,需要实现其方法供子视图调用:

  1. -(void)saveBookInfo:(EditViewController *)controller{
  2. if (self.BookList==nil) {
  3. self.BookList=[[NSMutableArray alloc]init];
  4. }
  5. Book *book=controller.OriginalBook;
  6. [self.BookList addObject:book];
  7. //将文件整体写入之后更新数据
  8. [NSKeyedArchiver archiveRootObject:self.BookList toFile:self.BookPath];
  9. [self.tableView reloadData];
  10. }

 子视图的.h文件中的声明:

  1. #import <UIKit/UIKit.h>
  2. #import "Book.h"
  3.  
  4. @class EditViewController;
  5.  
  6. #pragma mark - 自定义委托
  7. @protocol CustomEditViewControllerDelegate <NSObject>
  8.  
  9. //定义一个方法,在根视图中保存数据
  10. - (void)saveBookInfo:(EditViewController *)controller;
  11.  
  12. @end
  13.  
  14. @interface EditViewController : UITableViewController <UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource,
  15. UINavigationControllerDelegate>
  16.  
  17. @property (weak, nonatomic) id<CustomEditViewControllerDelegate> customDelegate;
  18.  
  19. @property (strong,nonatomic) Book *OriginalBook;
  20.  
  21. @property (weak, nonatomic) IBOutlet UIImageView *converImage;
  22.  
  23. @property (weak, nonatomic) IBOutlet UITextField *bookNameText;
  24.  
  25. @property (weak, nonatomic) IBOutlet UITextField *authorText;
  26.  
  27. @property (weak, nonatomic) IBOutlet UITextField *priceText;
  28.  
  29. @end

  其中需要注意的是自定义的委托,需要传递一个子视图,先用Class声明一下使用到的类,子视图也比较简单,选择图片之前有一篇博客已经写过如何使用,其他的就是控件赋值,详细代码如下:

  1. //
  2. // EditViewController.m
  3. // MySearchBar
  4. //
  5. // Created by keso on 15/2/4.
  6. // Copyright (c) 2015年 keso. All rights reserved.
  7. //
  8.  
  9. #import "EditViewController.h"
  10.  
  11. @interface EditViewController ()
  12.  
  13. @end
  14.  
  15. @implementation EditViewController
  16.  
  17. - (void)viewDidLoad {
  18. [super viewDidLoad];
  19. // Uncomment the following line to preserve selection between presentations.
  20. // self.clearsSelectionOnViewWillAppear = NO;
  21. // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
  22. // self.navigationItem.rightBarButtonItem = self.editButtonItem;
  23. }
  24.  
  25.  
  26. - (IBAction)chooseConverImage:(id)sender {
  27. UIImagePickerController *picker=[[UIImagePickerController alloc]init];
  28. // 指定照片源
  29. [picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
  30. // 指定是否允许修改
  31. [picker setAllowsEditing:YES];
  32. // 指定代理
  33. [picker setDelegate:self];
  34. // 显示照片选择控制器
  35. [self.navigationController presentViewController:picker animated:YES completion:nil];
  36.  
  37. }
  38. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  39. UIImage *image = info[@"UIImagePickerControllerEditedImage"];
  40. //设置图片
  41. [self.converImage setImage:image];
  42. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  43.  
  44. }
  45.  
  46.  
  47. - (IBAction)saveBook:(id)sender {
  48. if (self.OriginalBook==nil) {
  49. self.OriginalBook=[[Book alloc]init];
  50. }
  51. //书籍名称
  52. _OriginalBook.BookName=_bookNameText.text;
  53. //封面
  54. _OriginalBook.ConverPicture=_converImage.image;
  55. _OriginalBook.Author=_authorText.text;
  56. _OriginalBook.Price=[[NSNumber alloc] initWithFloat:[_priceText.text floatValue]];
  57. // 通知父视图控制器(用户列表)保存用户记录,并且返回
  58. [_customDelegate saveBookInfo:self];
  59. //返回到上级视图
  60. [self.navigationController popViewControllerAnimated:YES];
  61.  
  62. }
  63.  
  64.  
  65. - (void)didReceiveMemoryWarning {
  66. [super didReceiveMemoryWarning];
  67. // Dispose of any resources that can be recreated.
  68. }
  69.  
  70.  
  71.  
  72. @end

  这个也算是一个委托的小Demo吧,比昨天那两个稍微好点,用到的知识点之前的博客中已经写过,如果有问题可以共同探讨,如有不当,可以评论区交流,感激不尽~