繁体   English   中英

在已加载子视图(UIView)的UIViewController中单击按钮

[英]Click button in a UIViewController that was loaded a subView (UIView)

我正在尝试将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)
}

}

如果要使其目标正确指向下面的功能,应在哪里设置目标或包括此功能? 我试过了:

  • 在UIViewController中而不是UIView中设置目标
  • 将该功能保留在UIView中

功能如下:

// 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)        
}

非常感谢您的帮助-谢谢!

是的, 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为您执行所有内部匹配检测。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM