【问题标题】:Swift4 addTarget at UIButton doesnt work in UIViewUIButton 的 Swift addTarget 在 UIView 中不起作用
【发布时间】:2018-03-30 06:02:51
【问题描述】:

我以编程方式创建了一个 UIButton 并将其添加到子视图中。 AddTarget 虽然在那里不起作用。 AddTarget 仅在我将按钮添加到主视图时才有效。

self.view.addSubview(button)

而不是

ViewSystem.addSubview(button)

有人知道为什么吗?

这里是完整代码:

class ViewController: UIViewController {

var ViewSystem = UIView()
@objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)

func ButtonCreate () {

    let button = UIButton()
    button.frame = CGRect(x: 50, y: 100, width: 70, height: 70)
    button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
    button.backgroundColor = UIColor.red
    button.tag=5
    ViewSystem.addSubview(button)

    self.view.addSubview(ViewSystem)
    }
}

【问题讨论】:

  • 可以添加button.isUserInteractionEnabled = true
  • 尝试 ViewSystem.clipsToBounds = true。我相信你不会看到你的按钮
  • 你没有指定ViewSystem的框架

标签: swift uibutton subview addtarget


【解决方案1】:

发生这种情况是因为您将按钮框架设置为 graterthen 您的视图,这就是您的按钮未点击的原因。

你没有设置你的视图框架,然后你怎么能在你的视图中设置你的按钮。

我在这里更新你的 ButtonCreate () 函数代码,它运行良好。

func ButtonCreate () {
            ViewSystem.frame = CGRect(x: 50, y: 100, width: 200, height: 70)
            ViewSystem.backgroundColor = .blue
            let button = UIButton()
            button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
            button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
            button.backgroundColor = UIColor.red
            button.tag = 5
            ViewSystem.clipsToBounds = false
            ViewSystem.addSubview(button)

            self.view.addSubview(ViewSystem)
        }

希望对您有所帮助,节省您的时间

【讨论】:

  • 帮了很多忙,谢谢!我刚刚接受了另一个答案,因为它是早些时候发布的。可悲的是我不能同时接受
  • 感谢您的重播
  • 我投了赞成票。这是迄今为止我遇到的同一问题的最佳和最简单的答案。
【解决方案2】:

您必须为您的 ViewSystem 提供框架。并且 ViewSystem 的高度宽度应该大于按钮的 X 和 Y。

    var ViewSystem = UIView()
ViewSystem.frame = CGRect(x: 50, y: 100, width: 70, height: 70)

@objc func TestPressed(sender: UIButton?) {Test.text=String((sender?.tag)!)

func ButtonCreate () {

    let button = UIButton()
    button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
    button.addTarget(self, action: #selector(TestPressed), for: .touchUpInside)
    button.backgroundColor = UIColor.red
    button.tag=5
    ViewSystem.addSubview(button)

    self.view.addSubview(ViewSystem)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多