簡體   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