ios - 获取 iOS View 的实际尺寸

标签 ios uiview addsubview

如何获得我正在控制的 View 或 subview 的实际尺寸?例如:

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 对象超出了它所添加到的 View 的尺寸。

考虑到这一点(假设有许多对象被添加为 subview ),如何确定 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;

关于ios - 获取 iOS View 的实际尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14854286/

相关文章:

ios - 添加 UIViewControllers View 作为另一个 UIViewController View 的 subview

objective-c - 将 UITableViewController 添加到其他 View

ios - 使用自动布局和大小类调整 Uibutton 的大小

ios - 如何设置tableViewIndex的自定义宽度?

ios - 自定义 UITableViewCell 中的按钮操作会影响其他单元格

ios - 重用类最佳实践

cocoa - 特立独行问题 : While adding a subview on NSView

ios - 通知 iVar 值变化

ios - 带有分页和缩放的 UIImage 或 UIImageView 单击

ios - Storyboard和自动布局 : how to set UIView to use same aspect ratio as device?