Swift中的UIButton没有注册 [英] UIButton in Swift is not registering touches
问题描述
我正在尝试使用Swift创建一个UIButton。它编译得很好,我可以在模拟器中看到我的按钮,但是当我点击它时,没有任何反应。这是我正在使用的代码:
I'm trying to create a UIButton using Swift. It compiles fine and I can see my button in the simulator, but when I click it, nothing happens. This is the code I am using:
let settings = UIButton()
settings.addTarget(self, action: "touchedSet:", forControlEvents: UIControlEvents.TouchUpInside)
settings.setTitle("Settings", forState: .Normal)
settings.frame = CGRectMake(0, 530, 150, 50)
scrollView.addSubview(settings)
在同一个类中,这是函数'touchingSet':
In the same class, here is the function 'touchedSet':
func touchedSet(sender: UIButton!) {
println("You tapped the button")
}
我正在使用模拟器,因为我没有iOS 8.0设备,可能是问题?
I'm using the simulator as I don't have an iOS 8.0 device, could that be the problem?
谢谢!
推荐答案
我认为这是一个老问题但我昨天刚遇到了类似的问题。我的按钮在触摸时突出显示但没有触发动作。
I see it is an old question but I just faced very similar problem yesterday. My buttons were highlighted on touch but not firing the action.
我有两个视图控制器。一个视图覆盖其他视图,按钮位于顶视图。
I have two view controllers. One view covers the others view and button is on the top view.
例如。
-
Rootviewcontroller有后视图
Rootviewcontroller has back view
Topviewcontroller有顶视图
Topviewcontroller has top view
如果我没有将topviewcontroler添加为rootviewcontroller的childviewcontroller,则顶视图上的按钮不会调用该操作。将topviewcontroller作为childviewcontroller添加后,它开始工作。
The button on top view does not call the action if I don't add the topviewcontroler as childviewcontroller of the rootviewcontroller. After adding the topviewcontroller as childviewcontroller it started to working.
简而言之:只是尝试将按钮superview的视图控制器作为childviewcontroller添加到父视图viewcontroller中,具体如下:方法
So in short: just try to add the view controller of buttons superview as childviewcontroller to the parent views viewcontroller with the following method
func addChildViewController(_ childController: UIViewController)
这篇关于Swift中的UIButton没有注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!