添加按钮到以编程方式创建的UIView

时间:2015-12-02 07:14:43

标签: ios swift button uiview

我以编程方式创建了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)

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

但结果就是这个

enter image description here

我的代码出了什么问题?

提前致谢

3 个答案:

答案 0 :(得分:5)

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

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 :(得分:4)

您应该使用bounds而不是视图的框架。

button.frame = newView.bounds

Bounds在其自己的坐标空间中返回视图坐标的CGRect,而frame返回相同但在其父坐标空间中的CGRect。

所以newView.bounds会返回像(0,0,width_of_newView,height_of_newview)

这样的CGRect

答案 2 :(得分:1)

你的按钮框错了。

当你声明一个帧的x和y属性时,它与它的superview相关。

因为您将按钮框架声明为(4,39,宽度,高度),它将被放置在视图框架中的坐标x = 4,y = 39上,这与您的图片完全相同。

如果你想让它像你的视图一样,将x和y改为0。