我正在尝试将UIView子视图添加到UIViewController中,并且UIView有一个希望用户能够切换的UISwitch。根据状态,UITextField的值将来回切换。以下是子视图(InitialView):
import UIKit
class InitialView: UIView {
// All UI elements.
var yourZipCodeSwitch: UISwitch = UISwitch(frame: CGRectMake(UIScreen.mainScreen().bounds.width/2 + 90, UIScreen.mainScreen().bounds.height/2-115, 0, 0))
override func didMoveToSuperview() {
self.backgroundColor = UIColor.whiteColor()
yourZipCodeSwitch.setOn(true, animated: true)
yourZipCodeSwitch.addTarget(ViewController(), action: "yourZipCodeSwitchPressed:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(yourZipCodeSwitch)
}
}如果我想让它的目标正确地指向下面的函数,我应该在哪里设置目标或者包含这个函数?我试过:
以下是功能:
// Enable/disable "Current Location" feature for Your Location.
func yourZipCodeSwitchPressed(sender: AnyObject) {
if yourZipCodeSwitch.on
{
yourTemp = yourZipCode.text
yourZipCode.text = "Current Location"
yourZipCode.enabled = false
}
else
{
yourZipCode.text = yourTemp
yourZipCode.enabled = true
}
}这里是我将其加载到UIViewController中的地方:
// add initial view
var initView : InitialView = InitialView()
// Execute on view load
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(initView)
}任何帮助都是非常感谢的--谢谢!
发布于 2015-07-30 22:09:01
是的,didMoveToSuperView()的安置没什么意义。因此,您正在创建一个随机的、完全不连接的ViewController实例,以使编译器高兴,但您的项目却令人难过。控制代码在控制器中,视图代码在视图中。
你需要在你真正的ViewController里
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(initView)
// Note 'self' is the UIViewController here, so we got the scoping right
initView.yourZipCodeSwitch.addTarget(self, action: "yourZipCodeSwitchPressed:", forControlEvents: .ValueChanged)
}另外,.TouchUpInside是用于UIButton的,切换开关要复杂得多,因此它们的事件是不同的。在切换开关的当前设置上触摸内部可以也不应该做任何事情,而在相反的设置上触摸内部会触发上面的控制事件。iOS为你做所有的内部命中检测。
https://stackoverflow.com/questions/31734143
复制相似问题