【问题标题】:UICollectionViewCell's subview absolute frameUICollectionViewCell 的子视图绝对框架
【发布时间】:2016-02-05 04:29:01
【问题描述】:

一直遇到这个我认为很容易解决的问题,但花了很多时间解决它却没有结果。

所以,我有一个 UIViewController,其中包含 UICollectionView。这个集合从顶部开始填充 75 像素,并且单元格的设置非常简单 - 只需设置 1 个 UIImageView 以适应容器的大小。一切都是用 AutoLayout 制作的。

我的任务是让 UIImageView 在点击时全屏显示。我正在做的是制作一个临时的 UIImageView 并添加到 UIViewController 视图的层次结构中。

我面临的问题是我无法在我点击的单元格中获得 UIImageView 的绝对框架。

我尝试了各种方法来计算框架,我最近的尝试是

var rect = cell.imageView.superview!.convertRect(cell.imageView.frame, toView: self.view)

但是,它返回的结果似乎忽略了集合视图顶部约束。

更新

原来我的问题是我从集合视图中获取单元格的方式错误。而不是:

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UIImageCollectionViewCell

我正在使用

let cell = self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! UIImageCollectionViewCell

这显然会导致创建一个带有错误框架的新单元格。我糟糕的、深夜编码有时并不是最好的事情。感谢Arun Ammannaya 的快速示例

【问题讨论】:

    标签: swift uiimageview autolayout uicollectionview uicollectionviewcell


    【解决方案1】:

    这是我试过的,按预期工作。

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    @IBOutlet var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCellWithReuseIdentifier("aaa", forIndexPath: indexPath)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 10
    }
    
    @IBAction func frame(sender: AnyObject) {
    
        print(String(sender.frame))
    
        let rect = sender.superview??.convertRect(sender.frame, toView: self.view)
    
        print(String(rect))
    
        let addedView = UIView()
        view.addSubview(addedView)
        addedView.frame = rect!
    
        addedView.backgroundColor = UIColor.yellowColor()
    }
    

    }

    故事板看起来像:

    输出如下:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多