繁体   English   中英

获取iOS视图的实际尺寸

[英]Get actual dimensions of iOS view

我如何获得我正在控制的视图或子视图的实际尺寸? 例如:

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0,200,100)];
[self addSubview:firstView];

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 230, 120)];
[firstView addSubview:button];

如您所见,我的button对象超出了要添加到的视图的尺寸。

考虑到这一点(假设有许多对象被添加为子视图),我如何确定firstView的实际宽度和高度?

如果您希望按钮具有与firstView相同的宽度和高度,则应使用UIView的bounds属性,如下所示:

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0,200,100)];
[self addSubview:firstView];

UIButton *button = [[UIButton alloc] initWithFrame:firstView.bounds];
[firstView addSubview:button];

要获得firstView的宽度/高度,您可以执行以下操作:

CGSize size = firstView.bounds.size;
NSInteger width = size.width;
NSInteger height = size.height;

第一个视图确实是200 x 100.但是,除非使用clipsToBounds否则不会剪切内部clipsToBounds

解决问题的首选方法是停止添加超出维度的视图或停止调整视图大小,以便它们在适当的时候溢出可用空间。

(实际计算包括层次结构中所有子视图的完整边界并不难,只是很多工作实际上不会让你到任何地方UIView碰巧允许视图比它们的容器大,但它不一定给出关于什么会正常工作的任何保证,如果被利用,很可能成为错误的来源clipsToBounds的原因可能是剪辑是昂贵的,但在动画期间必须临时移出界限以实现效果在将它们从视图中删除之前。)

firstview.frame.size.width firstview.frame.size.height

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM