UICollectionViewCell不适合设备屏幕

时间:2015-11-17 23:42:29

标签: ios xcode swift uicollectionview

我正在尝试使UICollectionViewCell适合屏幕宽度。

在界面构建器中,它看起来像这样:

当我在iPhone 6上构建并运行时,它看起来像这样:

(如你所见,我想填补左右两侧的宽度。

我尝试在cellForItemAtIndexPath

中添加此内容
cell.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, cell.bounds.size.height)

但这使得单元格移动到右侧,因此它的一部分单元格从屏幕视图中移出..

我的cellForItemAtIndexPath看起来像这样:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell  

        cell.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, cell.bounds.size.height)

        cell.flagContentButton.titleLabel?.adjustsFontSizeToFitWidth = true
        cell.uploadedTimeLabel.adjustsFontSizeToFitWidth = true
        cell.imageText.adjustsFontSizeToFitWidth = true

        cell.layer.borderWidth = 0.5
        cell.layer.cornerRadius = 3
        let myColor : UIColor = UIColor(red: 0.0, green: 0.0, blue:0.0, alpha: 0.15)
        cell.backgroundColor = UIColor.whiteColor()
        cell.layer.borderColor = myColor.CGColor

        if (self.arrayOfDetails.count > indexPath.row){
            let post = self.arrayOfDetails[indexPath.row]
            cell.imageText.text = post.text
            cell.objectID.append(post.objID)
            cell.uploadedTimeLabel.text = post.CreatedAt.timeAgo

            cell.imageView.setImageWithUrl(NSURL(string: post.image)!, placeHolderImage: UIImage(named: "Placeholder"))
        }

        return cell
    }

修改

我尝试添加此代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        // Code below
        return CGSizeMake(UIScreen.mainScreen().bounds.size.width, 126)
    }

这使宽度适合,但图像和文字没有移动: Image here

1 个答案:

答案 0 :(得分:0)

看起来你是UIEdgeInsets在iOS 8+上默认为零的受害者。您可以在Interface Builder中设置它们:

或代码:

<强>的UITableView:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

<强> UICollectionView:

将代理UICollectionViewDelegateFlowLayout添加到视图控制器界面,然后:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
相关问题