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

标签 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

我的代码有什么问题?

提前致谢

最佳答案

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

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)

关于ios - 将按钮添加到以编程方式创建的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34036891/

相关文章:

android - 防止按钮在 Android 上隐藏软键盘

iphone - 上传离线数据和上传失败的数据

iphone - 禁用 iPhone 4S/new iPad 键盘上的听写按钮

ios - 一起水平滚动 UICollectionView 的所有行

java - 我的程序将无法继续播放音频

jquery-mobile - 禁用按钮在单击时隐藏标题

ios - 为什么 iOS 等宽字体的行为不是那样的?

ios - 为 Google Maps iOS 应用缩放级别条件

ios - 从图像数组创建动画

ios - 如何在 Swift 中设置按钮图像