我以编程方式创建了 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 完全相同的位置、宽度和高度
但是结果是这样的
我的代码有什么问题?
提前致谢
最佳答案
问题是由这行代码引起的:
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/