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

目录

一. 图文混排(自动调整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.
     }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容