[英]Add Button to UIView Created Programmatically
I created UIView and Button programmatically 我以编程方式创建了UIView和Button
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)
I want the button to be inside the UIView, and to have exactly the same location, width and height of UIView 我希望按钮位于UIView内,并且具有与UIView完全相同的位置,宽度和高度
but the result is this 但结果是这样
What is wrong with my code ? 我的代码有什么问题?
Thanks in advance 提前致谢
The issue is caused by this line of code: 此问题是由以下代码行引起的:
button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height)
In your current implementation the x position of button is 4 and y position is 39, that's why you are getting the result like that way. 在当前的实现中,button的x位置为4,y位置为39,这就是为什么要以这种方式获得结果的原因。 You need to specify the button frame relative to the newView. 您需要指定相对于newView的按钮框架。
Change the button frame setting code to: 将按钮框设置代码更改为:
button.frame = CGRectMake(0, 0, width, height)
You should use bounds
instead of the frame of the view. 您应该使用bounds
而不是视图的框架。
button.frame = newView.bounds
Bounds returns the CGRect of the view coordinates in its own coordinate space, while frame returns the same but in it's parent's coordinate space. Bounds在其自己的坐标空间中返回视图坐标的CGRect,而frame在其父坐标空间中返回相同的CGRect。
So newView.bounds would return a CGRect like (0,0,width_of_newView,height_of_newview)
因此newView.bounds将返回一个CGRect,例如(0,0,width_of_newView,height_of_newview)
your button frame is wrong. 您的按钮框是错误的。
when you declared x and y property of a frame, it is related to its superview. 当您声明框架的x和y属性时,它与其父视图相关。
since you declare your button frame as (4, 39, width, height) it will be placed on coordinate x = 4, y = 39 in view's frame which is exactly like your picture. 由于您将按钮框声明为(4,39,宽度,高度),因此它将被放置在与您的图片完全相同的视图框中,坐标x = 4,y = 39。
if you want to make it like your view, change x and y to 0. 如果要使其像您的视图一样,请将x和y更改为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.