我正在尝试使UIView缩小并移动到另一个中心点。当用户点击某个UICollectionViewCell时,它开始,然后以该单元格为中心制作一个新的UIView,并开始扩展直到填满整个屏幕。这很好。我将单元格的原始中心点存储在新的UIView(具有属性originCenter的自定义类)中。
let expandingCellView = SlideOverView(frame: cell.bounds)
expandingCellView.center = collectionView.convert(cell.center, to: self)
expandingCellView.textLabel.text = cell.textLabel.text
expandingCellView.originWidth = cell.bounds.width
expandingCellView.originHeight = cell.bounds.height
expandingCellView.originCenter = self.convert(expandingCellView.center, to: self)
expandingCellView.originView = self
self.addSubview(expandingCellView)
expandingCellView.widthConstraint.constant = self.frame.width
expandingCellView.heightConstraint.constant = self.frame.height
UIView.animate(withDuration: 0.3, animations: {
expandingCellView.center = self.center
expandingCellView.layoutIfNeeded()
})
此代码工作正常。现在,我向该扩展视图添加了一个按钮,该按钮执行以下代码:
widthConstraint.constant = originWidth
heightConstraint.constant = originHeight
print(self.convert(self.originCenter, to: nil))
UIView.animate(withDuration: 0.5, animations: {
self.center = self.convert(self.originCenter, to: nil)
self.layoutIfNeeded()
}, completion: { (done) in
// self.removeFromSuperview()
})
将视图缩小到原始大小效果很好。唯一不起作用的是居中。我将原始单元格中心点转换为该视图坐标系。这会产生我认为正确的坐标。但是,所有视图仅移至屏幕的左上方。
下面是指向屏幕录像的链接。第一个UIView将其新中心点打印为(208.75,411.75),我打开的第二个UIView将其中心打印为(567.25,411.75)。这些值对我来说似乎是正确的,但是正如您在视频中看到的那样,它们并没有移到这一点。有什么办法可以解决吗?
即使将新中心设置为例如CGPoint(x: 500, y: 500)
,视图仍将移动到x = 149.5和y = 149.5
创建具有对单元格的var
引用的weak
weak var selectedCell: UICollectionViewCell!
在CollectionView
委托didSelectItemAt
呼叫中分配选定的单元格>
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedCell = collectionView.cellForItemAtIndexPath(indexPath) }
在将
expandingCellView
添加为子视图之后,执行此操作以使其从单元格大小变为全屏
// make expanding view the same size as cell expandingCellView.frame = selectedCell.frame // animate UIView.animate(withDuration: 0.5, animations: { self.expandingCellView.layoutIfNeeded() self.expandingCellView.frame = self.view.frame }, completion: { (_) in self.expandingCellView.layoutIfNeeded() })
只要将其反转以使其像单元格一样小
// animate UIView.animate(withDuration: 0.5, animations: { self.expandingCellView.layoutIfNeeded() self.expandingCellView.frame = self.selectedCell.frame }, completion: { (_) in self.expandingCellView.layoutIfNeeded() })
[
frame
使用全局位置。