如何以编程方式在uicollectionview中插入图像?
我很新的Objective-C所以希望这一切都有道理..我跑第一个答案中提供的代码创build一个UICollectionView以编程方式 ..它工作正常。现在我想添加一些图片单元格,可以通过鼠标点击。我search了很多教程,但都使用nib文件或故事板文件。我可以通过编程来完成这个任务吗?
任何帮助将不胜感激。 提前致谢。
初学者先阅读tutroial,然后在下面的链接和苹果doc中先了解一下
IOS编程-uicollectionview-教程与样本代码
像这种方法改变你的背景颜色
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100]; recipeImageView.image = [UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]; cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]]; [self.view addSubview:recipeImageView]; cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]]; return cell; }
输出:
正如洛根所言:
#define IMG_TAG 1000 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... cell.textLabel.text = @"test....."; UIImage * img = [UIImage imageNamed: @"sampleImage"]; UIImageView * customImageView = (UIImageView*) [cell viewWithTag: IMG_TAG]; // two cases: // 1) we got a "recycled" cell, so we already have an image view added // 2) we got a "new" cell, so we must create, add image view AND TAg // in both cases we will set image if (customImageView){ // case 1 // nothing special }else{ // case 2: // add and tag: customImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 2, 30, 30)]; [cell addSubview: customImageView]; customImageView.tag = IMG_TAG; } customImageView.image = img; return cell; }
请审查和upvote 🙂
注意:
上面的代码是错误的!
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100]; recipeImageView.image = [UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]; cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]]; [self.view addSubview:recipeImageView]; cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:[recipeImages objectAtIndex:indexPath.row]]]; return cell; }
你分配(更好地分配ONCE的非标签…),但代码将添加子视图每个时间cellForItemAtIndexPath被调用。