gpt4 book ai didi

ios - 如何将手机图库中的图片添加到 UITableView

转载 作者:行者123 更新时间:2023-11-28 19:36:06 25 4
gpt4 key购买 nike

我在 Storyboard UITableView 中创建了原型(prototype)单元格、TableViewController 和 UITableViewCell。现在我想从手机图库中选择所有图片并将一张或多张保存到数据库中。但是此时我需要实现给tableview添加图片。我是 iOS 的初学者。谁能告诉我该怎么做?给我一个链接或代码?谢谢你的提前

最佳答案

您可以使用 AssetsLibrary 框架 中的 ALAssetsLibrary 从手机图库中获取所有图像。将每个图像保存到一个数组中。

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {

if(result != nil) {

if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {

NSURL *url= (NSURL*) [[result defaultRepresentation] url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
UIImage *img = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
[imgArray addbject:img];
}
failureBlock:^(NSError *error){ NSLog(@"operation failed"); } ];
}
}
};

然后您可以使用此数组保存到数据库或在表格 View 中显示。对于在 TableView 中使用,您需要在原型(prototype)单元格中添加 UIImageView,然后将数组中的图像相应地设置到单元格中。您的 TableView 委托(delegate)方法将如下所示。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [imgArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

CellId = @"ImageCell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
}
UIImage *img = [imgArray objectAtIndex:indexPath.row];
cell.imgView.image = img;
return cell;
}

关于ios - 如何将手机图库中的图片添加到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com