簡體   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