UI图像& UITableViewCell 尺寸
我通过 URL 动态加载不同大小的图像到我的 UITableViewCells 中。我希望能够根据下载的图像的大小调整单元格的大小。我可以提取尺寸然后更改每个单元格的 heightForRowAtIndexPath 吗?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[arrayOfImages objectAtIndex:indexPath.row]]
options:NSUncachedRead
error: &error];
UIImage *image = [[UIImage alloc] initWithData:receivedData];
imgView.image = image;
[cell.contentView addSubview:imgView];
....
I am loading into my UITableViewCells different sized images dynamically via URLs. I want to be able to resize the Cell depending on the size of the image that's downloaded. Can I extract the dimensions then change the heightForRowAtIndexPath for each cell?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[arrayOfImages objectAtIndex:indexPath.row]]
options:NSUncachedRead
error: &error];
UIImage *image = [[UIImage alloc] initWithData:receivedData];
imgView.image = image;
[cell.contentView addSubview:imgView];
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短的回答:一旦你有了图像,那么 image.size.height 应该给你你想要的。但是,heightForRowAtIndexPath: 在 cellForRowAtIndexPath: 之前被调用。因此,您可能想要实现某种类型的异步图像加载器。查看 Apple 示例 LazyTableImages 的完整实现。
长答案:我做了一些快捷方式来回答你的问题,而无需编写 1000 行代码,但这应该演示这个想法。重要的位是 cellForRowAtIndexPath: 和 heightForRowAtIndexPath:。
RootViewController.m
The short answer: once you have the image, then image.size.height should give you what you want. However, heightForRowAtIndexPath: gets called before cellForRowAtIndexPath:. So you will probably want to implement some type of async image loader. Have a look at the Apple sample LazyTableImages for a full implementation of that.
The long answer: I made a few shortcuts to answer your question without writing 1000 lines of code, but this should demonstrate the idea. The important bits are cellForRowAtIndexPath: and heightForRowAtIndexPath:.
RootViewController.m