UITableView 在ios里面算是很常用的的ui控件!
用来显示列表数据,当显示固定消息体的时候挺方便的!一旦遇到消息内容不一致,然后每行的高度都不一样的时候,
就需要我们自己来手动控制每行的高度啦!
先看看 UITableViewDelegate UITableViewDelegate 几个常用的方法!
// UITableView 构造CELL
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
// UITableView CELL 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
// UITableView 多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
// UITableView 每组多少个CELL
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
// UITableView 每行CELL 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
大概思路 , 先计算高度 ,然后设置每行高度,刷新UITableView。
我这里用到SDWebImage去执行下载图片。
下载成功后得到图片的高度,
通过委托去存储高度,然后改变CELL高度!/用来NSMutableDictionary存储每行CELL的高度 然后通过标示去取相对应的CELL高度。
先自定义CELL
#import <UIKit/UIKit.h>
@protocol ChaneCellHegith;
@interface LeftViewCell : UITableViewCell{
__unsafe_unretained id<ChaneCellHegith> _delegate;
}
@property(nonatomic,strong) IBOutlet UIImageView *menuIcon;
@property (nonatomic, assign) id<ChaneCellHegith> delegate;
@property(nonatomic ,assign) NSInteger cont;
@property(nonatomic ,assign) BOOL isLoad;
@property(nonatomic ,copy) NSString *iconPath;
@end
// 改变高度委托
@protocol ChaneCellHegith <NSObject>
-(void) chaneCellHegith :(NSInteger) hegith :(NSInteger) row;
@end
// 下载图片
- (void)setIconPath:(NSString *)iconPath
{
if (iconPath) {
__block LeftViewCell *blockSelf = self;
[_menuIcon setImageWithURL:[NSURL URLWithString:iconPath]
placeholderImage:[UIImage imageNamed:@"Icon.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
blockSelf.menuIcon.frame = CGRectMake(10, 10, image.size.height, image.size.height);
if (blockSelf.isLoad == NO) {
[blockSelf.delegate chaneCellHegith:image.size.height:blockSelf.cont];
blockSelf.isLoad = YES;
}
}];
}
}
UIViewController 实现该委托
- (void)chaneCellHegith :(NSInteger)hegith :(NSInteger)row
{
[allCellHeigth setObject:[NSString stringWithFormat:@"%i", hegith] forKey:[NSString stringWithFormat:@"%i", row]];
NSIndexPath *te = [NSIndexPath indexPathForRow:row inSection:0];
[_iTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:te, nil] withRowAnimation:UITableViewRowAnimationMiddle];
}
// UITableView item高度
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 返回相对应高度!
if ([allCellHeigth objectForKey:[NSString stringWithFormat:@"%i", indexPath.row
]]) {
return [[allCellHeigth objectForKey:[NSString stringWithFormat:@"%i", indexPath.row
]] floatValue];
}
return TabItemHeight;
}
大概就是这样 有时间了整理一个DEMO出来 ! 很多地方都可以优化,也有问题,大概思路是这样
剩下的就是大家去拓展了!