这篇是见过写的最为详细易懂的文章:
简单概括下:
1.bounds和frame都是属于CGRect类型的结构体,系统的定义如下,包含一个CGPoint(起点)和一个CGSize(尺寸)子结构体。
struct CGRect {
CGPoint origin;
CGSize size;
};
复制代码
2.frame 是子视图相对于父视图的位置origin和大小,其坐标系是参照父视图的坐标系
3.bounds是子视图本身的位置origin和大小,坐标系是参照本身坐标系,即 更改bounds中的位置对于当前视图没有影响,相当于更改了当前视图的坐标系,对于子视图来说当前视图的左上角已经不再是(0,0), 而是改变后的坐标,坐标系改了,那么所有子视图的位置也会跟着改变。
- frame不管对于位置还是大小,改变的都是自己本身。
- frame的位置是以父视图的坐标系为参照,从而确定当前视图在父视图中的位置。
- frame的大小改变时,当前视图的左上角位置不会发生改变,只是大小发生改变。
- bounds改变位置时,改变的是子视图的位置,自身没有影响;其实就是改变了本身的坐标系原点,默认本身坐标系的原点是左上角。
- bounds的大小改变时,当前视图的中心点不会发生改变,当前视图的大小发生改变,看起来效果就想缩放一样
以下是学习完后自制的简陋 scrollview
//
// ViewController.swift
// 自制scrollview
//
// Created by Mengduan on 2023/5/6.
//
import UIKit
let screenwidth = UIScreen.main.bounds.size.width
let screenhight = UIScreen.main.bounds.size.height
class ViewController: UIViewController {
lazy var ScreollView : UIView = {
let scrview = UIView(frame: CGRect(x: screenwidth/2-50, y: 70, width: 100, height: 600))
scrview.bounds.origin = CGPoint(x: 0, y: 0)
scrview.backgroundColor = .red
return scrview
}()
lazy var upButton : UIButton = {
let button = UIButton(frame: CGRect(x: 20, y: 800, width: 50, height: 50))
button.setTitle("up", for: .normal)
button.backgroundColor = .green
button.addTarget(self, action: #selector(upup), for: .touchUpInside)
return button
}()
lazy var downButton : UIButton = {
let button = UIButton(frame: CGRect(x: 260+40, y: 800, width: 50, height: 50))
button.setTitle("down", for: .normal)
button.backgroundColor = .green
button.addTarget(self, action: #selector(downdown), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
configUI()
}
func configUI(){
self.view.addSubview(ScreollView)
self.view.addSubview(upButton)
self.view.addSubview(downButton)
}
@objc func upup(){
ScreollView.frame.origin.y = ScreollView.frame.origin.y - 10
}
@objc func downdown(){
ScreollView.frame.origin.y = ScreollView.frame.origin.y + 10
}
}
用以加深对bounds和frame的理解
部分图文来源https://www.jianshu.com/p/7e3ed50b39a1