2015-12-02 43 views
-1

我创建的UIView和按钮编程Add按钮的UIView创建编程

var width = self.view.frame.width - 8 
     var height = width/8 

     newView.frame = CGRectMake(4, 39, width, height) 
     newView.backgroundColor = UIColor.greenColor() 
     self.view.addSubview(newView) 

     var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton 
     button.frame = newView.frame 
     button.backgroundColor = UIColor.whiteColor() 
     button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 
     button.setTitle(" All Hospitals/Clinics", forState: UIControlState.Normal) 
     button.setTitleColor(UIColor.blackColor(), forState: .Normal) 
     button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left 
     newView.addSubview(button) 

我希望按钮是UIView的内部,并具有完全相同的位置,宽度和UIView的

的高度

但结果是这样的

enter image description here

什么是错我的代码?

在此先感谢

+0

? –

+0

@ SohilR.Memon是的我正在使用autolayout,但我需要这个按钮被编程创建 – Maha

+0

然后,你必须在编程创建UI时也给出约束! –

回答

4

这个问题是由下面这行代码引起的:

button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height) 

在你当前实现按钮的x坐标为4和y位置是39,这就是为什么你得到结果就像那样。您需要指定相对于newView的按钮框架。

更改按钮框设置代码:

button.frame = CGRectMake(0, 0, width, height) 
1

你的按钮帧是错误的。

当您声明帧的x和y属性时,它与其超级视图有关。由于您将您的按钮框架声明为(4,39,宽度,高度),因此它将放置在坐标x = 4,y = 39的视图框架中,与您的图片完全相同。

,如果你想让它像你的观点,改变x和y为0

3

您应该使用bounds,而不是观点的框架。

button.frame = newView.bounds 

边界返回视图的坐标的CGRect在其自己的坐标空间,而帧返回相同的,但在它的父级坐标空间。

所以newView.bounds将您是否使用自动布局返回一个的CGRect喜欢(0,0,width_of_newView,height_of_newview)