我想要的是移动 UIViewB 并保持所有视图的位置,就像什么都没发生一样。 我想让viewC回到原来的地方,然后viewB被移动怎么办?无论 viewB 如何旋转,这都必须适用于所有角度。我怎样才能做到这一点?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Create UIViewA
let viewA = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
viewA.backgroundColor = .red
self.view.addSubview(viewA)
// Create UIViewB
let viewB = UIView(frame: CGRect(x: 150, y: 150, width: 200, height: 200))
viewB.backgroundColor = .green
viewA.addSubview(viewB)
// Create UIViewC
let viewC = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
viewC.backgroundColor = .blue
viewB.addSubview(viewC)
// Initial position of viewC in viewA's coordinate system
let initialCPositionInA = viewC.convert(viewC.bounds.origin, to: viewA)
// Rotate viewB by 45 degrees
viewB.transform = CGAffineTransform(rotationAngle: .pi / 4.5) // 45 degrees
// Calculate the movement delta of viewB
let movementDelta = CGPoint(x: 0, y: -50)
// Move viewB up by -50 pixels
viewB.center = CGPoint(x: viewB.center.x, y: viewB.center.y + movementDelta.y)
// I want viewC back to the original place before viewB is moved how ? This must apply to all angles regardless how viewB rotate
}
}
我尝试了许多不同的解决方案,通过移动 UIViewC 的 y 位置,但它返回奇怪的结果,因为有应用于 UIViewB 的变换也应用于 UIViewC。
您应该在视图 A 的坐标系(或任何固定的坐标系)中工作。
在视图 B 移动之前,获取视图 C 的中心(作为视图 A 中的坐标)。请记住,
center
是父级坐标系中的坐标。
let oldCenter = viewB.convert(viewC.center, to: viewA)
然后移动视图 B 后,将视图 C 的中心设置回
oldCenter
:
viewC.center = viewB.convert(oldCenter, from: viewA)