【问题标题】:Add Button to UIView Created Programmatically将按钮添加到以编程方式创建的 UIView
【发布时间】:2016-03-06 08:22:32
【问题描述】:

我以编程方式创建了 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 具有完全相同的位置、宽度和高度

但结果是这样的

我的代码有什么问题?

提前致谢

【问题讨论】:

  • 你在使用自动布局吗?
  • @SohilR.Memon 是的,我正在使用自动布局,但我需要以编程方式创建此按钮
  • 那么,您还必须在以编程方式创建 UI 时给予约束!
  • @SohilR.Memon UIView 和按钮的约束?这是这个问题的原因吗?即使他们有相同的框架?

标签: ios swift button uiview


【解决方案1】:

你可以使用Anchor

lazy var testButton: UIButton = {

  let button = UIButton()

  button.translatesAutoresizingMaskIntoConstraints = false
  button.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  button.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  button.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
  button.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

  return button

}()

override func viewDidLoad() {
  self.view.addSubview(testButton)
}

【讨论】:

    【解决方案2】:

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

    button.frame = newView.bounds
    

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

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

    【讨论】:

      【解决方案3】:

      你的按钮框架是错误的。

      当你声明一个框架的 x 和 y 属性时,它与它的父视图相关。

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

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

      【讨论】:

        【解决方案4】:

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

        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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-16
          • 2020-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多