UIView和它的子类都有frame和bounds属性。有什么不同?
当前回答
以上所有答案都是正确的,以下是我的看法:
为了区分框架和边界概念,开发者应该阅读:
相对于父视图(父视图),它包含在= FRAME中 相对于它自己的坐标系,决定了它的子视图location = BOUNDS
"bounds"是令人困惑的,因为它给人的印象是坐标是它所设置的视图的位置。但这些是有关系的,可以根据坐标系常数进行调整。
其他回答
框架是一个矩形,它定义了UIView相对于它的父视图。
bounds rect是定义NSView坐标系的值的范围。
也就是说,这个矩形中的任何东西都会显示在UIView中。
试着运行下面的代码
- (void)viewDidLoad {
[super viewDidLoad];
UIWindow *w = [[UIApplication sharedApplication] keyWindow];
UIView *v = [w.subviews objectAtIndex:0];
NSLog(@"%@", NSStringFromCGRect(v.frame));
NSLog(@"%@", NSStringFromCGRect(v.bounds));
}
这段代码的输出是:
机箱设备方向为纵向
{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}
机箱设备方向为横向
{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}
显然,你可以看到框架和边界之间的区别
框架与边界
If you create a view at X:0, Y:0, width:400, height:400, its frame and bounds are the same. If you move that view to X:400, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed. If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed. If you change the bounds then it will change the content inside the frame because the origin of the bounds rectangle starts at a different part of the view.
UIView的边界是一个矩形,表示为相对于它自己的坐标系(0,0)的位置(x,y)和大小(宽度,高度)。
UIView的框架是一个矩形,表示为相对于它所包含的父视图的位置(x,y)和大小(宽度,高度)。
因此,想象一个视图的大小为100x100(宽x高),位于其父视图的25,25 (x,y)处。下面的代码打印出这个视图的边界和框架:
// This method is in the view controller of the superview
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
NSLog(@"bounds.size.width: %f", label.bounds.size.width);
NSLog(@"bounds.size.height: %f", label.bounds.size.height);
NSLog(@"frame.origin.x: %f", label.frame.origin.x);
NSLog(@"frame.origin.y: %f", label.frame.origin.y);
NSLog(@"frame.size.width: %f", label.frame.size.width);
NSLog(@"frame.size.height: %f", label.frame.size.height);
}
这段代码的输出是:
bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100
frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100
我们可以看到,在这两种情况下,视图的宽度和高度是相同的不管我们是在看边界还是在看框架。不同之处在于视图的x,y定位。在边界的情况下,x和y坐标是0,0,因为这些坐标是相对于视图本身的。然而,坐标系x和y坐标是相对于视图在父视图中的位置(前面我们说过是在25,25)。
还有一个关于UIViews的很棒的演示。请看幻灯片1-20,它不仅解释了帧和边界之间的区别,而且还展示了可视化的例子。
Frame相对于SuperView,而Bounds相对于NSView。
例子:40 X = Y = 60。也包含3个视图。这张图向你展示了清楚的想法。
推荐文章
- 如何从UIImage (Cocoa Touch)或CGImage (Core Graphics)获取像素数据?
- 在Swift中如何调用GCD主线程上的参数方法?
- iOS -构建失败,CocoaPods无法找到头文件
- 为什么单元测试中的代码不能找到包资源?
- Xcode构建失败“架构x86_64未定义的符号”
- 新的自动引用计数机制是如何工作的?
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- 如何使用UIVisualEffectView来模糊图像?
- 自动调整掩码大小编程vs接口生成器/ xib / nib
- 我如何输入RGB值到接口生成器?
- 裁剪一个UIImage
- 在这个块中强烈地捕获self很可能导致保留循环
- iPhone上UIView和UILabels的渐变
- 自动布局- UIButton的固有大小不包括标题插入