ios技术知识分子iOS学习开发

D18:图文混排(自动调节高度)和多媒体

2015-05-31  本文已影响1101人  Vinc

目录

一. 图文混排(自动调整cell高度)

  1. 创建导航控制器, 建立模型
  2. 下载数据, 解析XML, 获得数据源
  3. 创建cell, 实现自动调节高度的功能
  4. tableView的代理方法中与之前项目的不同之处
  5. 去除自动布局, 使cell能正常显示

二. 多媒体

  1. 从相册选择图片
  2. 播放本地音频
  3. 播放视频
  4. 录音
  5. 拍照
  6. 录视频

一. 图文混排(自动调整cell高度)

  1. 创建导航控制器, 建立模型
  2. 下载数据, 解析XML, 获得数据源
  3. 创建cell, 实现自动调节高度的功能
     @implementation TweetCell
     
     - (void)showData:(TweetModel *)model
     {
         [self.headImageView sd_setImageWithURL:[NSURL URLWithString:model.portrait]];
         self.nameLabel.text = model.author;
         self.commentCountLabel.text = model.commentCount;
         
         // 存储当前的y值
         CGFloat y = 40;
     
     #warning
         // 描述
         // 计算描述文字的高度
         /* 
          第一个参数: 文字显示的最大范围
          第二个参数: 计算文字高度的方式
          第三个参数: 文字的属性(字体大小等等)
          第四个参数: 上下文(nil)
          */
         NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
         CGRect bodyFrame = [model.body boundingRectWithSize:CGSizeMake(270, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
         CGFloat bodyH = bodyFrame.size.height;
         
         // 设置文字的大小
         self.descLabel.text = model.body;
         self.descLabel.font = [UIFont systemFontOfSize:16];
         self.descLabel.numberOfLines = 0;
         
         CGRect descFrame = self.descLabel.frame;
         descFrame.size.height = bodyH;
         self.descLabel.frame = descFrame;
         
         // 更新当前的y值
         y += (bodyH + 10);
         
         // 图片
         if (model.imgSmall.length > 0) {
             // 有图片 显示图片
             [self.smallImageView sd_setImageWithURL:[NSURL URLWithString:model.imgSmall]];
             
             // 修改图片的位置
             CGRect imageFrame = self.smallImageView.frame;
             imageFrame.origin.y = y;
             self.smallImageView.frame = imageFrame;
             
             // 更新当前的y值
             y += (60 + 10);
             
             self.smallImageView.hidden = NO;
         } else {
             self.smallImageView.hidden = YES;
         }
         
         // 时间
         NSDateFormatter *df = [[NSDateFormatter alloc] init];
         // hh表示12小时制
         [df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
         
         // 把日期的字符串转化为时间对象
         NSDate *pubDate = [df dateFromString:model.pubDate];
         
         // 计算时间差
         NSDate *nowDate = [NSDate date];
         NSTimeInterval time = [nowDate timeIntervalSinceDate:pubDate];
         
         // 显示时间文字的字符串
         NSMutableString *timeString = [NSMutableString string];
         
         if (time > 3600) {
             int hour = (int)time / 3600;
             [timeString appendFormat:@"%d小时前", hour];
         } else if (time >= 60) {
             int min = (int)time / 60;
             [timeString appendFormat:@"%d分钟前", min];
         } else {
             [timeString appendFormat:@"%d秒前", (int)time];
         }
         
         // 来自的客户端
         if ([model.appclient isEqualToString:@"3"]) {
             [timeString appendString:@"  来自iPhone客户端"];
         } else if ([model.appclient isEqualToString:@"4"]) {
             [timeString appendString:@"  来自Android客户端"];
         }
         
         self.timeLabel.text = timeString;
         
         CGRect rect = self.timeLabel.frame;
         rect.origin.y = y;
         self.timeLabel.frame = rect;
     }
     
     + (CGFloat)heightWithModel:(TweetModel *)model
     {
         CGFloat height = 40;
         // 描述文字的高度
         NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
         CGFloat descH = [model.body boundingRectWithSize:CGSizeMake(270, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size.height;
         
         height += (descH + 10);
         
         // 图片
         if (model.imgSmall.length > 0) {
             height += 60 + 10;
         }
         
         // 时间
         height += (20 + 10);
         
         return height;
     }
    
  4. tableView的代理方法中与之前项目的不同之处
     - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
     {
         TweetModel *model = self.dataArray[indexPath.row];
         
         CGFloat h = [TweetCell heightWithModel:model];
         
         return h;
     }
    
  5. 去除自动布局, 使cell能正常显示

二. 多媒体

  1. 播放本地音频
     #import "AudioViewController.h"
     #import "MyUtility.h"
     #import <AVFoundation/AVFoundation.h>
     
     @interface AudioViewController ()
     {
         // 音频播放
         AVAudioPlayer *_player;
         // 滑块
         UISlider *_slider;
         // 定时器
         NSTimer *_timer;
     }
     
     @end
     
     @implementation AudioViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 播放按钮
         UIButton *playBtn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"播放" target:self action:@selector(playAction:)];
     
         // 暂停按钮
         UIButton *pauseBtn = [MyUtility creatBtnFrame:CGRectMake(100, 200, 80, 40) title:@"暂停" target:self action:@selector(pauseAction:)];
     
         // 停止按钮
         UIButton *stopBtn = [MyUtility creatBtnFrame:CGRectMake(100, 300, 80, 40) title:@"停止" target:self action:@selector(stopAction:)];
     
         [self.view addSubview:playBtn];
         [self.view addSubview:pauseBtn];
         [self.view addSubview:stopBtn];
         
         // 初始化定时器
         _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
                   
         // 创建滑块对象
         _slider = [[UISlider alloc] initWithFrame:CGRectMake(50, 400, 300, 20)];
         [self.view addSubview:_slider];
         // 添加事件
         [_slider addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventValueChanged];
     
     }
     
     - (void)timeAction:(id)sender
     {
         if (_player) {
             _slider.value = _player.currentTime;
         }
     }
     
     - (void)dealloc
     {
         if (_timer) {
             [_timer invalidate];
         }
     }
     
     - (void)slideAction:(id)sender
     {
         // 滑动时, 让音频播放到对应的位置
         if (_player) {
             _player.currentTime = _slider.value;
         }
     }
     
     - (void)playAction:(id)sender
     {
         // 播放本地音频
         NSString *path = [[NSBundle mainBundle] pathForResource:@"song" ofType:@"mp3"];
         NSURL *url = [NSURL fileURLWithPath:path];
         _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
         // 设置滑块的最大值
         _slider.maximumValue = _player.duration;
         
         // 播放
         [_player prepareToPlay];
         [_player play];
     }
     
     - (void)pauseAction:(id)sender
     {
         [_player pause];
     }
     
     - (void)stopAction:(id)sender
     {
         [_player stop];
         _player.currentTime = 0;
     }
    
  2. 播放视频
     #import "VideoViewController.h"
     #import "MyUtility.h"
     #import <MediaPlayer/MediaPlayer.h>
     @interface VideoViewController ()
     
     @property (nonatomic, strong) MPMoviePlayerViewController *moviePlayer;
     
     @end
     
     @implementation VideoViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 播放本地视频按钮
         UIButton *localBtn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"本地视频" target:self action:@selector(playLocal:)];
         
         // 播放网络视频按钮
         UIButton *netBtn = [MyUtility creatBtnFrame:CGRectMake(100, 200, 80, 40) title:@"网络视频" target:self action:@selector(playNet:)];
         
         [self.view addSubview:localBtn];
         [self.view addSubview:netBtn];
         self.view.backgroundColor = [UIColor whiteColor];
     }
     
     - (void)playLocal:(id)sender
     {
         // 本地路径
         NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];
         NSURL *fileUrl = [NSURL fileURLWithPath:path];
         // 初始化播放对象
         _moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:fileUrl];
         // 播放
         [_moviePlayer.moviePlayer prepareToPlay];
         [_moviePlayer.moviePlayer play];
         
         // 显示
         [self presentViewController:_moviePlayer animated:YES completion:nil];
     }
     
     - (void)playNet:(id)sender
     {
         // http://121.40.54.251:280/zhangchu/video/mp4/liangbanniuxinA.mp4
         NSURL *url = [NSURL URLWithString:@"http://121.40.54.251:280/zhangchu/video/mp4/liangbanniuxinA.mp4"];
         
         if (_moviePlayer) {
             [_moviePlayer.moviePlayer stop];
             _moviePlayer = nil;
         }
         
         _moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
         
         // 播放
         [_moviePlayer.moviePlayer prepareToPlay];
         [_moviePlayer.moviePlayer play];
         
         // 显示
         [self presentViewController:_moviePlayer animated:YES completion:nil];
     }
    
  3. 录音
     #import "RecordViewController.h"
     #import "MyUtility.h"
     #import <AVFoundation/AVFoundation.h>
     
     @interface RecordViewController ()
     
     // 录音
     @property (nonatomic, strong) AVAudioRecorder *recoder;
     @property (nonatomic, strong) AVAudioPlayer *player;
     
     @end
     
     @implementation RecordViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 录音按钮
         UIButton *recordBtn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"录音" target:self action:@selector(recordAction:)];
         
         // 停止录音按钮
         UIButton *stopBtn = [MyUtility creatBtnFrame:CGRectMake(100, 200, 80, 40) title:@"停止" target:self action:@selector(stopAction:)];
         
         // 播放按钮
         UIButton *playBtn = [MyUtility creatBtnFrame:CGRectMake(100, 300, 80, 40) title:@"播放" target:self action:@selector(playAction:)];
     
         [self.view addSubview:recordBtn];
         [self.view addSubview:stopBtn];
         [self.view addSubview:playBtn];
         
         self.view.backgroundColor = [UIColor whiteColor];
     }
     
     // 获取录制音频文件的路径
     - (NSString *)creatPath
     {
         NSString *path = [NSHomeDirectory() stringByAppendingString:@"Document/test.wav"];
         NSLog(@"%@", path);
         return path;
     }
     
     - (void)recordAction:(id)sender
     {
         // 录音
         // 1. 路径
         // 2. 属性
         NSMutableDictionary *dict = [NSMutableDictionary dictionary];
         //  1) 格式
         [dict setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
         //  2) 采样率
         [dict setObject:[NSNumber numberWithInt:1000] forKey:AVSampleRateKey];
         //  3) 声道
         [dict setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
         //  4) 采样位数
         [dict setObject:[NSNumber numberWithInt:32] forKey:AVLinearPCMBitDepthKey];
         //  5) 是否采用高位优先的采样方式
         [dict setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsBigEndianKey];
         //  6) 是否采用浮点数
         [dict setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsFloatKey];
     
         /*
          第一个参数: 录制文件存储的位置
          第二个参数: 录制的属性
          第三个参数: 错误信息
          */
         _recoder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:[self creatPath]] settings:dict error:nil];
         
         // 录制
         [_recoder prepareToRecord];
         [_recoder record];
         
     #warning 真机
         AVAudioSession *session = [AVAudioSession sharedInstance];
         [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
         [session setActive:YES error:nil];
     }
     
     - (void)stopAction:(id)sender
     {
         [_recoder stop];
     }
     
     - (void)playAction:(id)sender
     {
         _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self creatPath]] error:nil];
         
         [_player prepareToPlay];
         [_player play];
     }
    
  4. 从相册选择图片
     #import "AlbumViewController.h"
     #import "MyUtility.h"
     
     @interface AlbumViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
     
     @end
     
     @implementation AlbumViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 按钮, 点击弹出相册选择界面
         UIButton *btn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"相册" target:self action:@selector(showAlbum:)];
         [self.view addSubview:btn];
         
         self.view.backgroundColor = [UIColor whiteColor];
         
         // 图片视图
         UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 200, 200, 100)];
         imgView.tag = 200;
         [self.view addSubview:imgView];
     }
     
     - (void)showAlbum:(id)sender
     {
         // 显示相册
         UIImagePickerController *ctrl = [[UIImagePickerController alloc] init];
         // 设置类型
         ctrl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
         // 设置代理
         ctrl.delegate = self;
         // 显示相册
         [self presentViewController:ctrl animated:YES completion:nil];
         
     }
     
     #pragma mark - UIImagePickerController代理
     // 点击取消按钮调用
     - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
     {
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
     
     // 选中一张图片的时候调用
     - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
         // 获取图片对象
         UIImage *image = info[UIImagePickerControllerOriginalImage];
         
         // 显示出来
         UIImageView *myImageView = (UIImageView *)[self.view viewWithTag:200];
         myImageView.image = image;
         
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
    
  5. 拍照
     #import "TakePhotoViewController.h"
     #import "MyUtility.h"
     
     @interface TakePhotoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
     
     @end
     
     @implementation TakePhotoViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 按钮, 点击弹出相册选择界面
         UIButton *btn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"拍照" target:self action:@selector(takePhoto:)];
         [self.view addSubview:btn];
         
         self.view.backgroundColor = [UIColor whiteColor];
         
     }
     
     // 拍照
     - (void)takePhoto:(id)sender
     {
         UIImagePickerController *ctrl = [[UIImagePickerController alloc] init];
         // 设置代理
         ctrl.delegate = self;
         // 设置类型
         ctrl.sourceType = UIImagePickerControllerSourceTypeCamera;
         // 设置为拍照(跟录视频区分)
         ctrl.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
         
         // 显示出来
         [self presentViewController:ctrl animated:YES completion:nil];
     }
     
     #pragma mark - UIImagePickerController代理方法
     - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
     {
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
     
     - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
         UIImage *image = info[UIImagePickerControllerOriginalImage];
         
         // 存储到相册
         UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
         
         [picker dismissViewControllerAnimated:YES completion:nil];
     
     }
    
  6. 录视频
     #import "VideoRecordViewController.h"
     #import "MyUtility.h"
     #import <AssetsLibrary/AssetsLibrary.h>
     
     @interface VideoRecordViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
     
     @end
     
     @implementation VideoRecordViewController
     
     - (void)viewDidLoad {
         [super viewDidLoad];
         // Do any additional setup after loading the view.
         
         // 按钮, 点击弹出相册选择界面
         UIButton *btn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"📹" target:self action:@selector(videoRecord:)];
         [self.view addSubview:btn];
         
         self.view.backgroundColor = [UIColor whiteColor];
         
     }
     
     // 录制视频
     - (void)videoRecord:(id)sender
     {
         UIImagePickerController *ctrl = [[UIImagePickerController alloc] init];
         
         // 代理
         ctrl.delegate = self;
         // 类型
         ctrl.sourceType = UIImagePickerControllerSourceTypeCamera;
         // 媒体类型
         ctrl.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
         // 设置为录视频
         ctrl.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
         
         // 显示
         [self presentViewController:ctrl animated:YES completion:nil];
     }
     
     #pragma mark - UIImagePickerController代理方法
     -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
     {
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
     
     - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
         // 获取视频的地址
         NSURL *url = info[UIImagePickerControllerMediaURL];
         
         // 存到相册里
         ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
         
         [library writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error) {
             NSLog(@"%@", error);
         }];
         
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
     
     - (void)didReceiveMemoryWarning {
         [super didReceiveMemoryWarning];
         // Dispose of any resources that can be recreated.
     }
上一篇下一篇

猜你喜欢

热点阅读