iOS10 UI教程视图的边界与视图的框架
iOS10 UI视图的边界
在视图的几何形状中我们提到了视图属性中的一部分属性可以将定义的视图绘制在屏幕上。其中典型的3个属性为边界属性、框架属性以及中心位置属性。
bounds表示的就是边界属性,它是一个CGRect属性。它定义了该视图本身内部的坐标系统中的位置(origin)和大小(size)。在大多数情况下bounds中的origin属性为(x: 0, y: 0),size属性为视图的大小。在使用bounds时,我们不可以确定视图是如何绘制在UI层次结构中的。
iOS10 UI视图的框架
frame表示的就是框架属性,定义了视图图如何放置层次结构中。frame是一个CGRect属性,它类型与bounds属性,但是frame的origin属性决定了视图如何放置它的父视图中。
注意:bounds属性和frame属性类似,但有所不同,bounds指的是该视图本身内部的坐标系统中的位置和大小。参照点是本身的坐标系统,即为绝对坐标,而frame指的是该视图在设计界面坐标系统中的位置和大小。参照点是设计界面,即为相对坐标。
【示例1-4:Frame】以下我们将使用代码说明frame和bounds的不同。具体的操作步骤如下:
(1)打开ViewController.swift文件,编写代码,实现在屏幕上显示一个红色的空白视图,并且分别输出bounds和frame的位置和大小。代码如下:
-
import UIKit
-
class ViewController: UIViewController {
-
override func viewDidLoad() {
-
super.viewDidLoad()
-
// Do any additional setup after loading the view, typically from a nib.
-
let point=CGPoint(x: 67.0, y: 217.0)
-
let size=CGSize(width: 240.0, height: 128.0)
-
let rect=CGRect(origin: point, size: size)
-
let newView=UIView(frame: rect)
-
self.view.addSubview(newView)
-
newView.backgroundColor=UIColor.red
-
//输出bounds的位置
-
print("bounds.origin.x:\(newView.bounds.origin.x)")
-
print("bounds.origin.y:\(newView.bounds.origin.y)")
-
//输出bounds的大小
-
print("bounds.size.width:\(newView.bounds.size.width)")
-
print("bounds.size.height:\(newView.bounds.size.height)")
-
//输出frame的位置和大小
-
print("frame.origin.x:\(newView.frame.origin.x)")
-
print("frame.origin.y:\(newView.frame.origin.y)")
-
print("frame.size.width:\(newView.frame.size.width)")
-
print("frame.size.height:\(newView.frame.size.height)")
-
}
-
……
-
}
此时运行程序,会看到如图1.9所示的效果
图1.9 运行效果 图1.10 运行效果
此时会在应用程序输出窗口输出如下内容:
-
//bounds的位置和大小
-
bounds.origin.x:0.0
-
bounds.origin.y:0.0
-
bounds.size.width:240.0
-
bounds.size.height:128.0
-
//frame的位置和大小
-
frame.origin.x:67.0
-
frame.origin.y:217.0
-
frame.size.width:240.0
-
frame.size.height:128.0
注意:在以上这些情况中,frame和bounds的size是相同的,但是origin是不同的。
(2)修改vViewController.swift文件中的viewDidLoad()方法中的代码,实现空白视图的旋转,旋转后再分别输出bounds和frame的位置和大小。代码如下:
-
override func viewDidLoad() {
-
super.viewDidLoad()
-
// Do any additional setup after loading the view, typically from a nib.
-
let point=CGPoint(x: 67.0, y: 217.0)
-
let size=CGSize(width: 240.0, height: 128.0)
-
let rect=CGRect(origin: point, size: size)
-
let newView=UIView(frame: rect)
-
self.view.addSubview(newView)
-
newView.backgroundColor=UIColor.red
-
newView.transform=CGAffineTransform(rotationAngle: 45) //旋转
-
print("bounds.origin.x:\(newView.bounds.origin.x)")
-
……
-
}
此时运行程序,会看到如图1.10所示的效果。在应用程序输出窗口输出以下内容:
-
//bounds的位置和大小
-
bounds.origin.x:0.0
-
bounds.origin.y:0.0
-
bounds.size.width:240.0
-
bounds.size.height:128.0
-
//frame的位置和大小
-
frame.origin.x:69.5035357716888
-
frame.origin.y:145.270969771571
-
frame.size.width:234.992928456622
-
frame.size.height:271.458060456858
注意:在旋转视图后,bounds的位置和大小和在没有旋转视图之前是一样的。frame发生了变化,为了容纳旋转后的视图,尺寸会自动进行调整。
iOS10 UI教程视图的边界与视图的框架
相关阅读:iOS10 UI教程视图的几何形状
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29597077/viewspace-2128931/
,如需转载,请注明出处,否则将追究法律责任。