2014-10-29 51 views
0

我創建了一個基於輸入大小創建子視圖的方法,所以沒有定義和默認的角落CGRect值。我想要創建一個解僱按鈕,將位於左上角每個子視圖的角落。目前我使用這種方法來添加它,但問題在於CGRectMake的值不能是靜態的。獲取創建子視圖的動態座標ios

CGRect tapToDismissFrame = CGRectMake(50.0f, 50.0f, 400.0f, 400.0f); 

UIButton *tapToDismiss = [[UIButton alloc] initWithFrame:tapToDismissFrame]; 
tapToDismiss.backgroundColor = [UIColor clearColor]; 
tapToDismiss.titleLabel.font = [UIFont fontWithName:[NSString stringWithFormat:@"Helvetica-Bold"] size:20]; 
[tapToDismiss setTitle:@"⊗" forState:UIControlStateNormal]; 
[tapToDismiss setTitleColor:[UIColor colorWithRed:173.0/255.0 green:36.0/255.0 blue:36.0/255.0 alpha:1.0] forState:UIControlStateNormal]; 
[tapToDismiss addTarget:self action:@selector(tapToDismissClicked:) forControlEvents:UIControlEventTouchUpInside]; 
[self.maskView addSubview:tapToDismiss]; 

如何獲取動態值以便在左上角或右上角創建它。

+0

爲什麼不使用佈局約束來定位按鈕? – rdelmar 2014-10-30 00:19:25

回答

0

您應該使用CGGeometry函數爲您的解僱按鈕計算正確的框架。假設你創建了那個按鈕。之後,這裏是一個示例代碼:

[button sizeToFit]; 
CGRect maskViewBounds = self.maskView.bounds; 
CGFloat top = CGRectGetMinY(maskViewBounds); 
CGRect left = CGRectGetMaxX(maskViewBounds); 
CGFloat buttonHeight = button.size.height; 
CGFloat buttonWidth = button.size.width; 
CGFloat topMargin = 5.0f; 
CGFloat leftMargin = 5.0f; 
CGPoint buttonCenter = CGPointMake(top + buttonHeight/2.0 + topMargin, left - buttonWidth/2.0 - leftMargin); 
button.center = buttonCenter; 

注意:我沒有在Xcode中編寫此代碼。所以可能會出現類型錯誤。

+0

對不起,它不工作,我糾正了錯誤,但沒有使用 [tapToDismiss sizeToFit]; CGRect maskViewBounds = self.maskView.bounds; CGFloat top = CGRectGetMinY(maskViewBounds); CGFloat left = CGRectGetMaxX(maskViewBounds); CGFloat buttonHeight = tapToDismiss.frame.size.height; CGFloat buttonWidth = tapToDismiss.frame.size.width; CGFloat topMargin = 5.0f; CGFloat leftMargin = 5.0f; (頂部+ buttonHeight/2.0 + topMargin,left - buttonWidth/2.0 - leftMargin); tapToDismiss.center = buttonCenter; – iosMessenger 2014-10-29 23:12:10

+0

在哪個函數中你寫這個代碼? – mustafa 2014-10-29 23:13:24

+0

不,我的意思是,如果你在'viewDidLoad'中做這個東西,它將無法工作。因爲在調用viewDidLoad時沒有設置視圖幀。所以所有的計算都是基於錯誤的值。您應該將計算代碼移到'viewDidLayoutSubViews'方法中。 – mustafa 2014-10-29 23:34:25