D18:圖文混排(自動(dòng)調(diào)節(jié)高度)和多媒體

目錄

一. 圖文混排(自動(dòng)調(diào)整cell高度)

  1. 創(chuàng)建導(dǎo)航控制器, 建立模型
  2. 下載數(shù)據(jù), 解析XML, 獲得數(shù)據(jù)源
  3. 創(chuàng)建cell, 實(shí)現(xiàn)自動(dòng)調(diào)節(jié)高度的功能
  4. tableView的代理方法中與之前項(xiàng)目的不同之處
  5. 去除自動(dòng)布局, 使cell能正常顯示

二. 多媒體

  1. 從相冊(cè)選擇圖片
  2. 播放本地音頻
  3. 播放視頻
  4. 錄音
  5. 拍照
  6. 錄視頻

一. 圖文混排(自動(dòng)調(diào)整cell高度)

  1. 創(chuàng)建導(dǎo)航控制器, 建立模型
  2. 下載數(shù)據(jù), 解析XML, 獲得數(shù)據(jù)源
  3. 創(chuàng)建cell, 實(shí)現(xiàn)自動(dòng)調(diào)節(jié)高度的功能
     @implementation TweetCell
     
     - (void)showData:(TweetModel *)model
     {
         [self.headImageView sd_setImageWithURL:[NSURL URLWithString:model.portrait]];
         self.nameLabel.text = model.author;
         self.commentCountLabel.text = model.commentCount;
         
         // 存儲(chǔ)當(dāng)前的y值
         CGFloat y = 40;
     
     #warning
         // 描述
         // 計(jì)算描述文字的高度
         /* 
          第一個(gè)參數(shù): 文字顯示的最大范圍
          第二個(gè)參數(shù): 計(jì)算文字高度的方式
          第三個(gè)參數(shù): 文字的屬性(字體大小等等)
          第四個(gè)參數(shù): 上下文(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;
         
         // 設(shè)置文字的大小
         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;
         
         // 更新當(dāng)前的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;
             
             // 更新當(dāng)前的y值
             y += (60 + 10);
             
             self.smallImageView.hidden = NO;
         } else {
             self.smallImageView.hidden = YES;
         }
         
         // 時(shí)間
         NSDateFormatter *df = [[NSDateFormatter alloc] init];
         // hh表示12小時(shí)制
         [df setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
         
         // 把日期的字符串轉(zhuǎn)化為時(shí)間對(duì)象
         NSDate *pubDate = [df dateFromString:model.pubDate];
         
         // 計(jì)算時(shí)間差
         NSDate *nowDate = [NSDate date];
         NSTimeInterval time = [nowDate timeIntervalSinceDate:pubDate];
         
         // 顯示時(shí)間文字的字符串
         NSMutableString *timeString = [NSMutableString string];
         
         if (time > 3600) {
             int hour = (int)time / 3600;
             [timeString appendFormat:@"%d小時(shí)前", hour];
         } else if (time >= 60) {
             int min = (int)time / 60;
             [timeString appendFormat:@"%d分鐘前", min];
         } else {
             [timeString appendFormat:@"%d秒前", (int)time];
         }
         
         // 來(lái)自的客戶端
         if ([model.appclient isEqualToString:@"3"]) {
             [timeString appendString:@"  來(lái)自iPhone客戶端"];
         } else if ([model.appclient isEqualToString:@"4"]) {
             [timeString appendString:@"  來(lái)自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;
         }
         
         // 時(shí)間
         height += (20 + 10);
         
         return height;
     }
    
  4. tableView的代理方法中與之前項(xiàng)目的不同之處
     - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
     {
         TweetModel *model = self.dataArray[indexPath.row];
         
         CGFloat h = [TweetCell heightWithModel:model];
         
         return h;
     }
    
  5. 去除自動(dòng)布局, 使cell能正常顯示

二. 多媒體

  1. 播放本地音頻
     #import "AudioViewController.h"
     #import "MyUtility.h"
     #import <AVFoundation/AVFoundation.h>
     
     @interface AudioViewController ()
     {
         // 音頻播放
         AVAudioPlayer *_player;
         // 滑塊
         UISlider *_slider;
         // 定時(shí)器
         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];
         
         // 初始化定時(shí)器
         _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
                   
         // 創(chuàng)建滑塊對(duì)象
         _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
     {
         // 滑動(dòng)時(shí), 讓音頻播放到對(duì)應(yīng)的位置
         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];
         // 設(shè)置滑塊的最大值
         _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:)];
         
         // 播放網(wǎng)絡(luò)視頻按鈕
         UIButton *netBtn = [MyUtility creatBtnFrame:CGRectMake(100, 200, 80, 40) title:@"網(wǎng)絡(luò)視頻" 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];
         // 初始化播放對(duì)象
         _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) 采樣位數(shù)
         [dict setObject:[NSNumber numberWithInt:32] forKey:AVLinearPCMBitDepthKey];
         //  5) 是否采用高位優(yōu)先的采樣方式
         [dict setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsBigEndianKey];
         //  6) 是否采用浮點(diǎn)數(shù)
         [dict setObject:[NSNumber numberWithBool:YES] forKey:AVLinearPCMIsFloatKey];
     
         /*
          第一個(gè)參數(shù): 錄制文件存儲(chǔ)的位置
          第二個(gè)參數(shù): 錄制的屬性
          第三個(gè)參數(shù): 錯(cuò)誤信息
          */
         _recoder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:[self creatPath]] settings:dict error:nil];
         
         // 錄制
         [_recoder prepareToRecord];
         [_recoder record];
         
     #warning 真機(jī)
         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. 從相冊(cè)選擇圖片
     #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.
         
         // 按鈕, 點(diǎn)擊彈出相冊(cè)選擇界面
         UIButton *btn = [MyUtility creatBtnFrame:CGRectMake(100, 100, 80, 40) title:@"相冊(cè)" 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
     {
         // 顯示相冊(cè)
         UIImagePickerController *ctrl = [[UIImagePickerController alloc] init];
         // 設(shè)置類型
         ctrl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
         // 設(shè)置代理
         ctrl.delegate = self;
         // 顯示相冊(cè)
         [self presentViewController:ctrl animated:YES completion:nil];
         
     }
     
     #pragma mark - UIImagePickerController代理
     // 點(diǎn)擊取消按鈕調(diào)用
     - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
     {
         [picker dismissViewControllerAnimated:YES completion:nil];
     }
     
     // 選中一張圖片的時(shí)候調(diào)用
     - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
     {
         // 獲取圖片對(duì)象
         UIImage *image = info[UIImagePickerControllerOriginalImage];
         
         // 顯示出來(lái)
         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.
         
         // 按鈕, 點(diǎn)擊彈出相冊(cè)選擇界面
         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];
         // 設(shè)置代理
         ctrl.delegate = self;
         // 設(shè)置類型
         ctrl.sourceType = UIImagePickerControllerSourceTypeCamera;
         // 設(shè)置為拍照(跟錄視頻區(qū)分)
         ctrl.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
         
         // 顯示出來(lái)
         [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];
         
         // 存儲(chǔ)到相冊(cè)
         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.
         
         // 按鈕, 點(diǎn)擊彈出相冊(cè)選擇界面
         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];
         // 設(shè)置為錄視頻
         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];
         
         // 存到相冊(cè)里
         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.
     }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容