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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39273437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:11:41  来源:igfitidea点击:

Swift : How to set Custom UICollectionViewCell as circle?

iosswiftxcodeuicollectionviewuicollectionviewcell

提问by Jayprakash Dubey

I've custom UICollectionViewCellthat contains UILabeland UIImage. I want to set the cell in circular format.

我有UICollectionViewCell包含UILabel和的自定义UIImage。我想以圆形格式设置单元格。

Note:-sizeForItemAtIndexPathcannot be changed due to AutoLayout.

注意:-sizeForItemAtIndexPath由于 AutoLayout 无法更改。

Below is code that I've used :

以下是我使用过的代码:

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

截图 1

Design screen

设计画面

回答by onCompletion

This is my UICollectionView Example which you can check for your solution. I am using storyboard to setup the primary collectionView with AutoLayout. Also, attaching some screenshots to clarify the result.

这是我的 UICollectionView 示例,您可以检查您的解决方案。我正在使用故事板来设置带有 AutoLayout 的主要 collectionView。此外,附上一些屏幕截图以阐明结果。

There is a method called drawRect(). You can use that inside your collectionView Cell class for doing the UI stuffs.

有一种方法叫做drawRect()。你可以在你的 collectionView Cell 类中使用它来做 UI 的事情。

Now here is my code.

现在这是我的代码。

1. ViewController.swift//Just the normal UIViewControllerlike yours, nothing else... :)

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//Just a UICollectionViewCellclass for dequeuing the cell.

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
    }

}

Note: I am not using either any flowlayoutof UICollectionViewFlowLayoutor cell size inside sizeForItemAtIndexPathfor this collectionView. You can add those things too. Please do some experiments as per your needs. BTW I am using Xcode 7.3.1 and Swift 2.2.

注:我没有使用任何任何flowlayoutUICollectionViewFlowLayout或细胞内的大小sizeForItemAtIndexPath此的CollectionView。你也可以添加这些东西。请根据您的需要做一些实验。顺便说一句,我使用的是 Xcode 7.3.1 和 Swift 2.2。

Here is the storyboard screenshot for collectionView setup and result on the simulator. First Storyboard screenshot with simulator result

这是模拟器上 collectionView 设置和结果的故事板截图。 带有模拟器结果的第一个 Storyboard 屏幕截图

Second Storyboard screenshot with simulator result

带有模拟器结果的第二个 Storyboard 屏幕截图

Hope this helped. Sorry for any mistake.

希望这有帮助。抱歉,有任何错误。

回答by Sandy

Just try to give corner radius as height/2, make sure cell should have same height and width.

只需尝试将角半径设置为高度/ 2,确保单元格应具有相同的高度和宽度。

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

cell.layer.masksToBounds = true

Please, let me know if this works for you.

请让我知道这是否适合您。

回答by Nirav D

The problem is cell's widthand heightis changed at run time according to your screen width, So to solve this issue add one square UIViewinside your cell and use that UIViewinside cellForItemAtIndexPathmethod to make it circle view like this.

问题是单元格的,widthheight在运行时根据您的屏幕宽度进行更改,因此要解决此问题,UIView请在单元格内添加一个正方形并使用该UIView内部cellForItemAtIndexPath方法使其成为这样的圆形视图。

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

回答by Mubin Mall

By giving this line for calculating the height of your cell

通过给出这条线来计算你的单元格的高度

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

You cant achieve what you want. Use Aspect Ratio technique. For Height and width of cell use your screen width and based on that aspect ratio update your cell height and width then and only then this line works....

你无法实现你想要的。使用纵横比技术。对于单元格的高度和宽度,请使用您的屏幕宽度,并根据该纵横比更新您的单元格高度和宽度,然后该行才有效....

If you need clarification skype me iammubin38

如果你需要澄清Skype我iammubin38

回答by Anand Nimje

You can try UICollectionViewDelegateFlowLayout ....

你可以试试 UICollectionViewDelegateFlowLayout ....

Add delegate first.

首先添加委托。

 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
        }
    }

回答by Arun Ammannaya

Use this updated cell.

使用这个更新的单元格。

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)
    }
}

回答by Rajesh Maurya

Hey check this code.

嘿检查这个代码。

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;
}