2014-10-29 53 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