文章目录
- 1. 坐标转换
- 2. 布局转换
- 3. 包含、相交
如:有3个色块
let view1 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 300.0, height: 300.0))
view1.backgroundColor = UIColor.cyan
self.view.addSubview(view1)
let view2 = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0))
view2.backgroundColor = .red
view1.addSubview(view2)
let view3 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0))
view3.backgroundColor = .blue
view1.addSubview(view3)
1. 坐标转换
from: 从哪个坐标系 to: 到哪个坐标系
/// view1 上的 view2 在 self.view 上的位置
print("view2.center on self.view: \(view1.convert(view2.center, to: self.view))")
/// 同上
print("view2.center on self.view: \(self.view.convert(view2.center, from: view1))")
// print
// view2.center: (100.0, 100.0)
// view2.center on self.view: (200.0, 200.0)
// view2.center on self.view: (200.0, 200.0)
2. 布局转换
/// view1 上的 view2 在 self.view 上的位置
print("view2 on self.view: \(view1.convert(view2.frame, to: self.view))")
/// 同上
print("view2 on self.view: \(self.view.convert(view2.frame, from: view1))")
// print
// view2 on self.view: (150.0, 150.0, 100.0, 100.0)
// view2 on self.view: (150.0, 150.0, 100.0, 100.0)
3. 包含、相交
/// view1 是否包含 view2.center
print("view1 contains view2.center: \(CGRectContainsPoint(view1.frame, view2.center))")
/// view1 是否包含 view2
print("view1 contains view2: \(CGRectContainsRect(view1.frame, view2.frame))")
/// view2 和 view3 是否相交
print("view2 intersect view3: \(CGRectIntersectsRect(view2.frame, view3.frame))")
// print
// view1 contains view2.center: true
// view1 contains view2: false
// view2 intersect view3: true
github Demo