Swift:如何将自定义UICollectionViewCell设置为圆形?

7

我有一个自定义的UICollectionViewCell,里面包含UILabelUIImage

我想将单元格设置为圆形格式。

注意:由于自动布局,sizeForItemAtIndexPath无法更改。

以下是我使用的代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath ) -> CGSize {

          return CGSize(width: (self.objKeypadCollectionView.frame.size.width/3)-10, height: (self.objKeypadCollectionView.frame.size.height/4)-10)
    }

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let objKeypadCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("idKeypadCollectionViewCell", forIndexPath: indexPath) as! KeypadCollectionViewCell

        if (self.numberArray[indexPath.item])=="asda" {
            objKeypadCollectionViewCell.lblNumber.text = ""
            objKeypadCollectionViewCell.imgPrint.hidden = false
        }
        else if (self.numberArray[indexPath.item])=="Derterel" {
            objKeypadCollectionViewCell.lblNumber.text = self.numberArray[indexPath.item]
            objKeypadCollectionViewCell.imgPrint.hidden = true
        }
        else {
            objKeypadCollectionViewCell.imgPrint.hidden = true
            objKeypadCollectionViewCell.lblNumber.text = self.numberArray[indexPath.item]
            objKeypadCollectionViewCell.layer.borderColor = UIColor.lightGrayColor().CGColor
            objKeypadCollectionViewCell.layer.borderWidth = 1
            objKeypadCollectionViewCell.layer.cornerRadius = objKeypadCollectionViewCell.frame.size.width/2
        }
        return objKeypadCollectionViewCell
    }

Screenshot 1

Design screen


它是图像、按钮或集合视图单元格。 - Anbu.Karthik
如果您真的无法更改sizeForItemAtIndexPath实现,那么实现您想要的最简单的方法就是向单元格添加一个虚拟矩形视图,并在其上设置边框和圆角半径。 - Losiowaty
为什么不直接更改键盘类型来实现这个? - Desdenova
@Anbu.Karthik:这是一个标签,其cornerRadius被设置为使其成为圆形。 - Jayprakash Dubey
@JayprakashDubey - 检查更新后的答案,兄弟。 - Anbu.Karthik
显示剩余2条评论
8个回答

17

这是我的UICollectionView示例,供您查看解决方案。我使用故事板(Storyboard)和自动布局(AutoLayout)来设置主要的collectionView,并附加了一些屏幕截图以澄清结果。

有一个名为 drawRect() 的方法。您可以在collectionView单元格类中使用它来处理UI相关事项。

现在,这是我的代码。

1. ViewController.swift //就像您的普通UIViewController一样,没有其他的... :)

//
//  ViewController.swift
//  CollectionCheckCircle
//
//  Created by Tuhin Samui on 02/09/16.
//  Copyright © 2016 Tuhin Samui. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        collectionView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 200
    }


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

        return cellOfCollection
    }

}

2. CollectionViewCell.swift //仅为了从队列中出列单元格而创建的UICollectionViewCell类。

//
//  CollectionViewCell.swift
//  CollectionCheckCircle
//
//  Created by Tuhin Samui on 02/09/16.
//  Copyright © 2016 Tuhin Samui. All rights reserved.
//

import UIKit

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    override func drawRect(rect: CGRect) { //Your code should go here.
        super.drawRect(rect)
        self.layer.cornerRadius = self.frame.size.width / 2
    }

}
注意:我在这个collectionView中没有使用任何flowlayoutUICollectionViewFlowLayout,也没有在sizeForItemAtIndexPath中设置单元格大小。你也可以添加这些内容。根据你的需求进行一些实验。顺便说一句,我使用的是Xcode 7.3.1和Swift 2.2。
这是用于设置collectionView并在模拟器上显示结果的storyboard截图。 First Storyboard screenshot with simulator result 还有一个截图。 Second Storyboard screenshot with simulator result 希望这能有所帮助。对于任何错误,我表示抱歉。

4

尝试将圆角半径设置为高度的一半,确保单元格的高度和宽度相同。

cell.layer.cornerRadius = min(cell.frame.size.height, cell.frame.size.width) / 2.0

cell.layer.masksToBounds = true

请告诉我这对你是否有效。

高度和宽度是通过编程生成的。它根据设备尺寸而异。 - Jayprakash Dubey
然后最小值函数将被处理。请检查并告诉我。 - Sanoj Kashyap
这个不起作用。它显示椭圆形而不是圆形。 - Jayprakash Dubey
如果您的视图必须是正方形,那么现在您可以在单元格上添加另一个视图,并使用相同的解决方案将其制作成圆形。 - Sanoj Kashyap
这里的关键是drawRect方法。 - Aisha

1
问题在于单元格的宽度和高度会根据屏幕宽度在运行时发生变化,因此为了解决这个问题,在单元格内添加一个正方形的 UIView,并在 cellForItemAtIndexPath 方法中使用该 UIView,使其成为圆形视图,如下所示。
objKeypadCollectionViewCell.circleView.layer.borderColor = UIColor.lightGrayColor().CGColor
objKeypadCollectionViewCell.circleView.layer.borderWidth = 1
objKeypadCollectionViewCell.circleView.layer.cornerRadius = objKeypadCollectionViewCell.frame.size.width/2
objKeypadCollectionViewCell.circleView.layer.masksToBounds = true

1
使用此更新的单元格。
class KeypadCollectionViewCell: UICollectionViewCell {

    var circularBGLayer: CALayer!

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = UIColor.clearColor()
        circularBGLayer = CALayer()
        circularBGLayer.backgroundColor = UIColor.lightGrayColor().CGColor
        layer.addSublayer(circularBGLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        var frame = self.bounds
        frame.size.width = min(frame.width, frame.height)
        frame.size.height = frame.width
        circularBGLayer.bounds = frame
        circularBGLayer.cornerRadius = frame.width*0.5
        circularBGLayer.position = CGPoint(x: frame.midX, y: frame.midY)
    }
}

1
通过提供这行代码来计算您单元格的高度。
return CGSize(width: (self.objKeypadCollectionView.frame.size.width/3)-10, height: (self.objKeypadCollectionView.frame.size.height/4)-10)

你无法实现所需的功能。使用纵横比技术。对于单元格的高度和宽度,请使用屏幕宽度,并根据该纵横比更新单元格的高度和宽度,然后才能使此行起作用...如果需要澄清,请添加我的Skype账号:iammubin38。

0

In swift 5

import UIKit
import Kingfisher

class StoryCollectionViewCell: UICollectionViewCell {
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
// this override can make the circle

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        self.layer.cornerRadius = self.frame.size.width / 2
    }

}



0

你可以尝试使用UICollectionViewDelegateFlowLayout....

首先添加代理。

 class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
            let collectionWidth = CGRectGetWidth(collectionView.bounds);
                var itemWidth = collectionWidth / 3 - 1;
                return CGSizeMake(itemWidth, itemWidth);
            }
        }

        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
            return 1
        }

        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
            return 1
        }
    }

0

嘿,看看这段代码。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath ) -> CGSize {
CGSize size = CGSize(width: (self.objKeypadCollectionView.frame.size.width/3)-10, height: (self.objKeypadCollectionView.frame.size.height/4)-10);
CGFloat width = size.width;
CGFloat height = size.height;
  if (width < height) {
     height = width;
   } else {
     width = height;
   }
   return size;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接