我正在尝试使 UICollectionViewCell 适合屏幕宽度。
在界面构建器中,它看起来像这样:
当我在 iPhone 6 上构建并运行时,它看起来像这样:
(如您所见,我想填充左侧和右侧的宽度。
我尝试将其添加到 cellForItemAtIndexPath
中:
cell.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, cell.bounds.size.height)
但这会使单元格移到右侧,因此单元格的一部分超出了屏幕 View 。
我的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
最佳答案
看起来您是 iOS 8+ 上 UIEdgeInsets
默认不为零的受害者。您可以在 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:
将委托(delegate)UICollectionViewDelegateFlowLayout
添加到您的 View Controller 界面,然后:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, 0, 0, 0);
}
关于ios - UICollectionViewCell 不适合设备屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769222/