【问题标题】:Corner radius of a UIButton in UICollectionViewCell not workingUICollectionViewCell 中的 UIButton 的角半径不起作用
【发布时间】:2015-10-04 09:05:18
【问题描述】:

我在 ANY-ANY 故事板类型的 ViewController 中有一个 UICollectionView,并使用 swift 的自动布局。我已将 ViewController 的尺寸更改为 iPhone 5 的屏幕尺寸。

问题在于,UICollectionViewCell 中有一个按钮,我正在尝试制作该按钮。当我在 iPhone 5 中运行时,按钮会变成圆形,但如果我在 iPhone 6 或 6+ 中运行,它不会变成圆形。

下面是我在“cellForItemAtIndexPath”中使用的代码

    var btnImage = cell.contentView.viewWithTag(100) as UIButton
    btnImage.layer.masksToBounds = true
    btnImage.layer.cornerRadius = btnImage.frame.size.height/2

这段代码的结果如下

如果我使用下面的代码

    var btnImage = cell.contentView.viewWithTag(100) as UIButton
    btnImage.layoutIfNeeded()
    btnImage.layer.masksToBounds = true
    btnImage.layer.cornerRadius = btnImage.frame.size.height/2

结果如下

有没有人对这个问题有任何想法。 提前致谢。

【问题讨论】:

    标签: iphone swift autolayout uicollectionview


    【解决方案1】:

    适用于该问题的解决方案如下:

    cell.contentView.frame = cell.bounds //This is important line
    var btnImage = cell.contentView.viewWithTag(100) as UIButton
    btnImage.layoutIfNeeded() //This is important line
    btnImage.layer.masksToBounds = true
    btnImage.layer.cornerRadius = btnImage.frame.size.height/2
    

    上面的代码使按钮完整的圆形。

    【讨论】:

      【解决方案2】:

      不能使用集合视图单元格的圆形矩形。我刚刚创建了一个演示应用程序来测试它并且它可以工作。下面是我的演示代码。

      override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
          var cell:CollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionCell
      
          // Configure the cell
          cell.roundTestButton.layer.cornerRadius = 10.0
          cell.roundTestButton.layer.masksToBounds = true
      
          println(cell.roundTestButton)
      
          return cell
      }
      

      或完整项目的here is git link

      【讨论】:

      • 我想让按钮完整的圆形。我从 git 下载了您的代码,并将该行替换为“ cell.roundTestButton.layer.cornerRadius = cell.roundTestButton.frame.size.height/2 ”并在 iPhone 6+ 上运行,这不是完整的圆形,而是变成了椭圆形。
      • @TeenanathPaul 我没有把它做成圆形我只是确保圆形矩形在 UICollectionViewCell 上工作得很好。
      • 谢谢@rptwsthi,我得到了解决方案,按钮现在是完整的圆形。
      【解决方案3】:

      这是由于自动布局限制。因为设置圆角半径大小后高度和宽度可以增加。尝试在情节提要中设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-05
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多