zoukankan      html  css  js  c++  java
  • 音频

     

    音频

     

     

    #import <AVFoundation/AVFoundation.h>

     

     

    一,点不同按键取不同字典

    二,根据获取到的字典取图片数组,作为图片动画

    三,取声音数组(需要判断有无),随机,播放

     

     

        //把本地文件地址转成url

        NSURL *url = [NSURL fileURLWithPath:audioPath];

     

        //创建音乐播放器,并赋值资源的url

        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

        //播放器会对播放资源进行预加载

        [_audioPlayer prepareToPlay];

        //播放

        [_audioPlayer play];

     

    //音量

    @property float volume;

    //播放状态

    @property(readonly, getter=isPlaying) BOOL playing;

    //播放、暂停、停止

    - (BOOL)play;

    - (void)pause;

    - (void)stop;

     

    //播放进度

    @property NSTimeInterval currentTime;

    //总时长

    @property(readonly) NSTimeInterval duration;

     

     

     

     

    // 注册self的观察者身份(拥有一个监听事件,开始监听整个工程中changeMusic的广播,只要监听到就执行changeMusicByNotification:方法)

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeMusicByNotification:) name:@"changeMusic" object:nil];

     

    - (void)changeMusicByNotification:(NSNotification *)noti

    {

    //[noti object]指的就是广播带的参数

    }

     

     

    // 使用观察者模式传值 (开始发送changeMusic广播,收到这个广播的监控者会执行自己的方法)

    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeMusic" object:musicName];

     

    //需要在合适的时候要取消观察者身份

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeMusic" object:nil];

     

     

     

     

    【label的动态高度】

     

     

    //根据一个字符串和字体算出一个size,宽度超过200以后自动加一行的高度(本例中宽最多200,高最多9999)

    CGSize size;

    //判断设备版本号

        if ([UIDevice currentDevice].systemVersion.floatValue>=7.0f) {

    //iOS7新方法

            size = [str boundingRectWithSize:CGSizeMake(200, 9999) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:label.font forKey:NSFontAttributeName] context:nil].size;

        } 

    else {

    //iOS7以前的方法

            size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(200, 9999)];

        }

     

    //然后修改label的frame(位置不变,只改变大小)

     

     

    ------------------------------------------------------------------------------------分割------------------------------------------------------------------------------------

        

    #import <UIKit/UIKit.h>

    #import <AVFoundation/AVFoundation.h>

     

    // 遵守音乐播放器协议,实现回调方法

    @interface GCZRootViewController : UIViewController<AVAudioPlayerDelegate>

     

    @end

     

    #import "GCZRootViewController.h"

    #import "GCZMusicListViewController.h"

     

    @interface GCZRootViewController ()

     

    // 声明一个音频播放器指针,音频播放是用这个对象来实现的

    @property(strong) AVAudioPlayer* player;

     

    // 声明一个IBOutlet指针,控制它的进度变化

    @property(strong) IBOutlet UISlider* processSlider;

    // 声明控制声音的slider指针,可以随时访问到它当前表示的音量

    @property(strong) IBOutlet UISlider* volumSlider;

    // 显示当前歌曲的播放进度

    @property (strong, nonatomic) IBOutlet UILabel *timeLabel;

     

    // 保存歌曲名字的字符串

    @property (strong) NSString* musicName;

    @property (strong, nonatomic) IBOutlet UILabel *nameLabel;

     

     

     

    - (IBAction)playMusic:(UIButton *)sender;

    - (IBAction)stopBt:(id)sender;

    // 选择歌曲的按钮

    - (IBAction)selectMusic:(UIButton *)sender;

     

     

    // 控制音量大小的方法

    - (IBAction)volumChanged:(UISlider*)sender;

    // 控制进度条的方法

    - (IBAction)processChanged:(UISlider*)sender;

    - (IBAction)processDidChanged:(id)sender;

     

    @end

     

    @implementation GCZRootViewController

     

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

    {

        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

        if (self) {

            // Custom initialization

        }

        return self;

    }

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

        

        // 注册self的观察者身份

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeMusicByNotification:) name:@"changeMusic" object:nil];

        

        

        if (_musicName.length == 0) {

            _musicName = @"蓝莲花";

        }

        

        _nameLabel.text = _musicName;

        NSString* path = [[NSBundle mainBundle] pathForResource:_musicName ofType:@"mp3"];

        // 封装本地路径为URL对象

        NSURL* url = [NSURL fileURLWithPath:path];

        

        // 初始化音频播放器对象

        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

        // 设置音频播放器委托

        _player.delegate = self;

        // 加载本地资源到内存

        [_player prepareToPlay];

    }

     

    - (void)changeMusicByNotification:(NSNotification*)noti

    {

        // 保存当前选中歌曲的名字

        _musicName = [noti object];

        // 更新标签显示的歌曲名

        _nameLabel.text = _musicName;

        // 清空一下_player之前的播放路径

        if (_player!=nil) {

            _player = nil;

        }

        

        // 更新player的播放路径

        NSString* path = [[NSBundle mainBundle] pathForResource:_musicName ofType:@"mp3"];

        // 封装本地路径为URL对象

        NSURL* url = [NSURL fileURLWithPath:path];

        

        // 初始化音频播放器对象

        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

        // 设置音频播放器委托

        _player.delegate = self;

        // 加载本地资源到内存

        [_player prepareToPlay];

        //[_player play];

        [self playMusic:nil];

    }

     

    - (void)didReceiveMemoryWarning

    {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    - (void)viewWillAppear:(BOOL)animated

    {

        [super viewWillAppear:animated];

     

    }

     

    // 更新UI的方法

    - (void)updateUI

    {

        // 获取当前播放器播放的音频的总时长

        NSTimeInterval allTime = _player.duration;

        // 获取当前播放器播放音频的当前进度

        NSTimeInterval curretnTime = _player.currentTime;

        // 设定显示条的当前进度

        _processSlider.value = curretnTime/allTime;

        

        int mm = (int)curretnTime/60;

        int ss = (int)curretnTime%60;

        NSString* currTimeString = [NSString stringWithFormat:@"%.2d:%.2d",mm,ss];

        

        int MM = (int)allTime/60;

        int SS = (int)allTime%60;

        NSString* durationTimeString = [NSString stringWithFormat:@"%.2d:%.2d",MM,SS];

        // 拼接一个包含当前播放时间和总时间的字符串

        NSString* resultString = [currTimeString stringByAppendingPathComponent:durationTimeString];

        

        _timeLabel.text = resultString;

    }

     

    - (IBAction)playMusic:(UIButton *)sender {

        

        // 根据控制声音的slider控件的值,来设置当前音量的大小

        [_player setVolume:_volumSlider.value];

        

        // 播放音频

        [_player play];

        

        // 使用时间管理器,设置每秒调用一次updateUI方法

        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateUI) userInfo:nil repeats:YES];

    }

     

    - (IBAction)stopBt:(id)sender {

        // 停止播放

        if ([_player isPlaying]) {

            [_player pause];

        }

    }

     

    - (IBAction)selectMusic:(UIButton *)sender {

        

        GCZMusicListViewController* musicVC = [[GCZMusicListViewController alloc] init];

        [self presentViewController:musicVC animated:YES completion:nil];

    }

     

    // 设置音量大小的方法

    - (IBAction)volumChanged:(UISlider*)sender

    {

        [_player setVolume:sender.value];

    }

     

    // 添加滑块控件关联的方法,控制歌曲进度变化

    - (IBAction)processChanged:(UISlider *)sender

    {

        // 先停止播放

        [self stopBt:nil];

        // 调整歌曲当前的播放进度

        _player.currentTime = sender.value*_player.duration;

        

        // 因为在这里播放会产生卡顿的感觉,所以我们处理的方式是在我们手指离开这个控件的时候再播放

    //    [self playMusic:nil];

    }

     

    // 当手指离开控制进度的slider时,调用的方法

    - (IBAction)processDidChanged:(id)sender

    {

        NSLog(@"process did changed");

        //开始播放

        [self playMusic:nil];

    }

     

    #pragma mark- AVAudioPlayerDelegate

    // 当播放完成时回调的方法

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

    {

        NSLog(@"finished");

    }

     

    // 当播放过程中被意外打断时调用,比如来电话

    - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player

    {

        NSLog(@"意外打断");

    }

     

    // 当意外中断结束时调用,比如接完电话

    - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags

    {

        NSLog(@"打断结束");

    }

     

    @end

     

     

     

     

     

    #import <UIKit/UIKit.h>

     

    @interface GCZMusicListViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

     

    @end

     

    #import "GCZMusicListViewController.h"

     

    @interface GCZMusicListViewController ()

     

    @property(strong) UITableView* tableView;

    @property(strong) NSMutableArray* dataSource;

     

    @end

     

    @implementation GCZMusicListViewController

     

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

    {

        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

        if (self) {

            // Custom initialization

        }

        return self;

    }

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

        

        _dataSource = [[NSMutableArray alloc] init];

        // 获取plist文件的路径

        NSString* path = [[NSBundle mainBundle] pathForResource:@"musicList" ofType:@"plist"];

        // 读取plist文件的内容

        NSArray* dataArr = [NSArray arrayWithContentsOfFile:path];

        // 加载数据源

        [_dataSource addObjectsFromArray:dataArr];

        

        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 30, 300, 460) style:UITableViewStylePlain];

        

        // 给表格式图设置一个背景图

        UIImageView* backView = [[UIImageView alloc] initWithFrame:_tableView.frame];

        backView.image = [UIImage imageNamed:@"king1.png"];

        [_tableView setBackgroundView:backView];

        

        _tableView.delegate = self;

        _tableView.dataSource = self;

        

        [self.view addSubview:_tableView];

    }

     

    - (void)didReceiveMemoryWarning

    {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    #pragma mark- 表格的数据源协议方法

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    {

        return _dataSource.count;

    }

    - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    {

        static NSString* identifier = @"gczCell";

     

        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];

     

        if (cell == nil) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

        }

        // 设置单元格的背景色为透明色,这样我们能看到背景图片

        cell.backgroundColor = [UIColor clearColor];

        // 显示歌曲的名字

        cell.textLabel.text = [_dataSource objectAtIndex:indexPath.row];

        return cell;

    }

     

    #pragma mark- UITableViewDelegate

    // 实现选中行方法,进行数据回传

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    {

        // 获取歌曲名

        NSString* musicName = [_dataSource objectAtIndex:indexPath.row];

        // 使用观察者模式传值

        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeMusic" object:musicName];

        

        // 移除视图

        [self dismissViewControllerAnimated:YES completion:nil];

        

    }

     

    @end

     

     

    ------------------------------------------------------------------------------------分割------------------------------------------------------------------------------------

    #import "ViewController.h"

    #import <AVFoundation/AVFoundation.h>

     

    @interface ViewController ()

     

    {

        NSDictionary *_dataDic;

        

        //音频播放器

        AVAudioPlayer *_audioPlayer;

    }

     

    @property (weak, nonatomic) IBOutlet UIImageView *bgView;

     

    @end

     

    @implementation ViewController

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Tomcat" ofType:@"plist"];

        _dataDic = [NSDictionary dictionaryWithContentsOfFile:path];

    }

     

    - (IBAction)btnClick:(UIButton *)sender

    {

        NSDictionary *subDic = nil;

        switch (sender.tag) {

            case 1:

            {

                subDic = [_dataDic objectForKey:@"cymbal"];

            }

                break;

            case 2:

            {

                subDic = [_dataDic objectForKey:@"fart"];

            }

                break;

            case 3:

            {

                subDic = [_dataDic objectForKey:@"eat"];

            }

                break;

            case 4:

            {

                subDic = [_dataDic objectForKey:@"drink"];

            }

                break;

            case 5:

            {

                subDic = [_dataDic objectForKey:@"scratch"];

            }

                break;

            case 6:

            {

                subDic = [_dataDic objectForKey:@"pie"];

            }

                break;

            default:

                break;

        }

        NSLog(@"%d==%@",sender.tag,[subDic objectForKey:@"comment"]);

        

        NSMutableArray *imageArr = [NSMutableArray array];

        for (int i = 0; i<[[subDic objectForKey:@"frames"] intValue]; i++) {

            [imageArr addObject:[UIImage imageNamed:[NSString stringWithFormat:[subDic objectForKey:@"imageFormat"],i]]];

        }

        

        _bgView.animationImages = imageArr;

        _bgView.animationDuration = imageArr.count/10;

        _bgView.animationRepeatCount = 1;

        [_bgView startAnimating];

        

        NSArray *soundArr = [subDic objectForKey:@"soundFiles"];

        

        if (!soundArr.count) {

            return;

        }

        

        //随机从数组里取元素

        NSString *soundName = [soundArr objectAtIndex:arc4random_uniform(soundArr.count)];

        

        NSString *soundPath = [[NSBundle mainBundle] pathForResource:soundName ofType:nil];

        

        if (_audioPlayer) {

            _audioPlayer = nil;

        }

        

        NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];

        

        //创建音频播放器

        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

        

        //预备

        [_audioPlayer prepareToPlay];

        

        //放

        [_audioPlayer play];

        

    }

     

    - (void)didReceiveMemoryWarning

    {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    @end

     

    ------------------------------------------------------------------------------------分割------------------------------------------------------------------------------------

    #import "ViewController.h"

    #import "SenconViewController.h"

     

    @interface ViewController ()

     

    @property (weak, nonatomic) IBOutlet UILabel *myLabel;

     

    @end

     

    @implementation ViewController

     

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    {

        SenconViewController *svc = [[SenconViewController alloc] init];

        [self presentViewController:svc animated:YES completion:nil];

    }

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

        //在通知中心里,添加一个观察者:self

        //当self监测到通知中心发送的@"fm90"这个消息,会立即执行listen这个方法

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listen:) name:@"fm90" object:nil];

    }

     

    - (void)listen:(NSNotification *)noti

    {

        //[noti object]发送广播时,带的参数

        NSString *textStr = [noti object];

        _myLabel.text = textStr;

        

        CGSize size = [textStr boundingRectWithSize:CGSizeMake(265, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil] context:nil].size;

        

        

        

        CGRect rect = _myLabel.frame;

        rect.size.width = size.width+5;

        rect.size.height = size.height+5;

        _myLabel.frame = rect;

    }

     

    - (void)dealloc

    {

        //在适当的时候需要取消观察者身份

        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"fm90" object:nil];

    }

     

     

    @end

     

     

    #import "SenconViewController.h"

     

    @interface SenconViewController ()

     

    @end

     

    @implementation SenconViewController

     

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

    {

        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

        if (self) {

            // Custom initialization

        }

        return self;

    }

     

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    {

        UITextView *tv = (UITextView *)[self.view viewWithTag:1];

        

        //通知中心发送一个@"fm90"的广播,带一个参数(tv.text)

        [[NSNotificationCenter defaultCenter] postNotificationName:@"fm90" object:tv.text userInfo:nil];

        

        [self dismissViewControllerAnimated:YES completion:nil];

    }

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

        // Do any additional setup after loading the view.

        self.view.backgroundColor = [UIColor brownColor];

        

        UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(20, 60, 200, 100)];

        tv.tag = 1;

        [self.view addSubview:tv];

        

    }

     

    - (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

     

    ------------------------------------------------------------------------------------分割------------------------------------------------------------------------------------

     

    #import <Foundation/Foundation.h>

     

    //前向声明(告诉编辑器MyConnection是一个类)

    @class MyConnection;

     

    @protocol MyConnectionDelegate <NSObject>

     

    //下载成功以后回调

    - (void)myConnctionDidFinish:(MyConnection *)mc;

     

    //下载失败以后回调

    - (void)myConnction:(MyConnection *)mc didFailWithError:(NSError *)error;

     

    @end

     

     

    @interface MyConnection : NSObject  <NSURLConnectionDataDelegate>

     

    {

        //网络请求

        NSURLRequest *_request;

    }

     

    //用来接收下载的数据

    @property (nonatomic, retain) NSMutableData *responseData;

     

    //代理指针

    @property (nonatomic, assign) id <MyConnectionDelegate> delegate;

     

    @property (nonatomic, assign) int tag;

     

    //接收一个字符串作为网址

    - (id)initWithUrlStr:(NSString *)urlStr;

     

    //开始异步下载

    - (void)starAsynchronous;

     

    //类方法创建对象

    + (MyConnection *)connectionWithUrlStr:(NSString *)urlStr delegate:(id<MyConnectionDelegate>)delegate;

     

    @end

     

     

    #import "MyConnection.h"

     

    @implementation MyConnection

     

    - (id)initWithUrlStr:(NSString *)urlStr

    {

        if (self = [super init]) {

            _request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:0 timeoutInterval:15];

            _responseData = [[NSMutableData alloc] init];

            NSLog(@"urlStr = %@",urlStr);

        }

        return self;

    }

     

    - (void)starAsynchronous

    {

        [NSURLConnection connectionWithRequest:_request delegate:self];

        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    }

     

    + (MyConnection *)connectionWithUrlStr:(NSString *)urlStr delegate:(id<MyConnectionDelegate>)delegate

    {

        MyConnection *mc = [[MyConnection alloc] initWithUrlStr:urlStr];

        mc.delegate = delegate;

        return mc;

    }

     

    #pragma mark - NSURLConnection

     

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

    {

        _responseData.length = 0;

    }

     

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    {

        [_responseData appendData:data];

    }

     

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection

    {

        //下载成功以后,调用代理的方法,传一个参数过去,参数就是用来下载的对象自己

        [self.delegate myConnctionDidFinish:self];

    }

     

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    {

        //下载失败了,告诉代理一声

        [self.delegate myConnction:self didFailWithError:error];

    }

     

    - (void)dealloc

    {

        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    }

     

    @end

     

     

    #import "ViewController.h"

    #import "MyConnection.h"

    #import "UIImageView+WebCache.h"

    #import "GDataXMLNode.h"

    #import "TweetCell.h"

    #import "TweetModel.h"

     

    @interface ViewController () <MyConnectionDelegate, UITableViewDataSource, UITableViewDelegate>

     

    {

        NSMutableArray *_dataArr;

        UITableView *_myTableView;

    }

     

    @end

     

    @implementation ViewController

     

    - (void)viewDidLoad

    {

        [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

        _dataArr = [[NSMutableArray alloc] init];

        

        MyConnection *mc = [MyConnection connectionWithUrlStr:@"http://www.oschina.net/action/api/tweet_list?uid=0&pageIndex=0&pageSize=20" delegate:self];

        [mc starAsynchronous];

        

        _myTableView = [[UITableView alloc] initWithFrame:self.view.frame];

        _myTableView.dataSource = self;

        _myTableView.delegate = self;

        [self.view addSubview:_myTableView];

    }

     

    #pragma mark - myConnection

     

    - (void)myConnctionDidFinish:(MyConnection *)mc

    {

        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:mc.responseData options:0 error:nil];

        

        NSArray *tweetArr = [document nodesForXPath:@"//tweet" error:nil];

        

        for (GDataXMLElement *tweetEle in tweetArr) {

            TweetModel *tm = [[TweetModel alloc] init];

            tm.portrait = [[[tweetEle elementsForName:@"portrait"] lastObject] stringValue];

            tm.author = [[[tweetEle elementsForName:@"author"] lastObject] stringValue];

            tm.body = [[[tweetEle elementsForName:@"body"] lastObject] stringValue];

            tm.imgSmall = [[[tweetEle elementsForName:@"imgSmall"] lastObject] stringValue];

            tm.pubDate = [[[tweetEle elementsForName:@"pubDate"] lastObject] stringValue];

            [_dataArr addObject:tm];

        }

        [_myTableView reloadData];

    }

     

    - (void)myConnction:(MyConnection *)mc didFailWithError:(NSError *)error

    {

        NSLog(@"%s",__func__);

    }

     

    #pragma mark - tableView

     

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    {

        return [_dataArr count];

    }

     

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    {

        TweetModel *tm = [_dataArr objectAtIndex:indexPath.row];

        

        CGFloat height = [tm.body boundingRectWithSize:CGSizeMake(195, CGFLOAT_MAX) options:1 attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil] context:nil].size.height;

        

        if (tm.imgSmall.length) {

            return 210 + height;

        }

        

        return 90 + height;

    }

     

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    {

        TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqq"];

        if (!cell) {

            cell = [[[NSBundle mainBundle] loadNibNamed:@"TweetCell" owner:self options:nil] lastObject];

        }

        

        TweetModel *tm = [_dataArr objectAtIndex:indexPath.row];

        

        [cell.portraitView setImageWithURL:[NSURL URLWithString:tm.portrait]];

        cell.authorLabel.text = tm.author;

        cell.bodyLabel.text = tm.body;

        

        CGSize size = [tm.body boundingRectWithSize:CGSizeMake(195, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:cell.bodyLabel.font, NSFontAttributeName, nil] context:nil].size;

        

        CGRect rect = cell.bodyLabel.frame;

        rect.size.width = size.width + 5;

        rect.size.height = size.height + 5;

        cell.bodyLabel.frame = rect;

        

        //判断用户留言中有没有图片

        if (tm.imgSmall.length) {

            cell.imgSmallView.hidden = NO;

            

            CGRect imageFrame = cell.imgSmallView.frame;

            imageFrame.origin.y = rect.origin.y + rect.size.height + 10;

            cell.imgSmallView.frame = imageFrame;

            

            [cell.imgSmallView setImageWithURL:[NSURL URLWithString:tm.imgSmall]];

            

            CGRect dateFrame = cell.pubDateLabel.frame;

            dateFrame.origin.y = imageFrame.origin.y + imageFrame.size.height + 10;

            cell.pubDateLabel.frame = dateFrame;

            

        } else {

            cell.imgSmallView.hidden = YES;

            

            CGRect dateFrame = cell.pubDateLabel.frame;

            dateFrame.origin.y = rect.origin.y + rect.size.height + 10;

            cell.pubDateLabel.frame = dateFrame;

        }

        

        return cell;

    }

     

    - (void)didReceiveMemoryWarning

    {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    @end

     

     

    #import <Foundation/Foundation.h>

     

    @interface TweetModel : NSObject

     

    @property (nonatomic, copy) NSString *portrait;

    @property (nonatomic, copy) NSString *author;

    @property (nonatomic, copy) NSString *body;

    @property (nonatomic, copy) NSString *imgSmall;

    @property (nonatomic, copy) NSString *pubDate;

     

    @end

    #import <UIKit/UIKit.h>

     

    @interface TweetCell : UITableViewCell

     

    @property (weak, nonatomic) IBOutlet UIImageView *portraitView;

    @property (weak, nonatomic) IBOutlet UILabel *authorLabel;

    @property (weak, nonatomic) IBOutlet UILabel *bodyLabel;

    @property (weak, nonatomic) IBOutlet UIImageView *imgSmallView;

    @property (weak, nonatomic) IBOutlet UILabel *pubDateLabel;

     

    @end

    让明天,不后悔今天的所作所为
  • 相关阅读:
    java基础-数组
    泛型 --集合
    单例模式(新)
    static 关键字
    单例模式
    迭代器模式(java版)
    Object类
    JavaWeb学习总结(十七)——JSP中的九个内置对象
    javaweb学习总结(十六)——JSP指令
    javaweb学习总结(十五)——JSP基础语法
  • 原文地址:https://www.cnblogs.com/-yun/p/4423120.html
Copyright © 2011-2022 走看看