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

Mah*_*aha 0 button uiview ios swift

我以编程方式创建了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)
Run Code Online (Sandbox Code Playgroud)

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

但结果就是这样

在此输入图像描述

我的代码出了什么问题?

提前致谢

Mid*_* MP 5

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

button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height)
Run Code Online (Sandbox Code Playgroud)

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

将按钮框设置代码更改为:

button.frame = CGRectMake(0, 0, width, height)
Run Code Online (Sandbox Code Playgroud)


moh*_*ish 5

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

button.frame = newView.bounds
Run Code Online (Sandbox Code Playgroud)

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

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