ios - 如何将数据从 UIViewsController 传递到 UIView,Swift

标签 ios swift uiview

我正在尝试将数据从我的 UIViewcoontroller 传递到 UIView。
我希望将金额值传递给 UIView,我需要它通过 UIView 中的按钮发送请求。

//this is my UIViewController

final class PayParkingViewController: BaseViewController {
    @IBOutlet weak var amount: UITextField!
//for example I need this myAmount value to be passed in my UIView
myAmount = amount.text
}
//This is my UIView
final class PaymentChoice: UIView {

    @IBOutlet weak var mastercard: UIButton!
    @IBOutlet var contentView: UIView!


      override init(frame: CGRect) {
         super.init(frame: frame)

         commonInit()
     }

     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         commonInit()
     }

     private func commonInit() {
             Bundle.main.loadNibNamed(className, owner: self, options: nil)
         guard let content = contentView else { return }
         addSubview(content)
         content.frame = bounds
         content.autoresizingMask = [.flexibleWidth, .flexibleHeight]
     }
    @IBAction func mastercardIsSelected(_ sender: Any) {

// here I need myAmount value from my UIViewController

    }

最佳答案

您首先在 View Controller 上创建一个属性,如下所示:

var completionHandler:((String) -> String)?

它是一个具有闭包类型的属性 completionHandler。闭包是可选的,用 ? 表示,闭包签名是 (String) -> String。这意味着闭包有一个字符串类型的参数并返回一个字符串类型的值。

再一次,在 View Controller 中,当文本被发送时调用闭包:
let myTextedAmount = completionHandler?(amount.text)

然后,在 View 中,您可以像这样定义闭包:
vc.completionHandler = { text in

    print("text = \(text)")

    return text
}

关于ios - 如何将数据从 UIViewsController 传递到 UIView,Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60109733/

相关文章:

javascript - 无法缩放 UIWebView

ios - UIImageJpgRepresentation 使图像分辨率加倍

iOS 9 - Xcode : "Follows Readable Width" programmatically

ios - UIView 自动调整大小

ios - Swift:以编程方式附加自定义 UIView

ios - 在Core Data中存储图像,如何清除缓存?

ios - 尝试在 TableView 中配置两个单元格时出现 "Fatal error: Index out of range"错误

ios - 我无法满足 IOS 8 今天扩展中的限制

ios - Swift:使用 prepareForSegue 将 UIView 容器的高度设置为嵌入式 UITableView 的高度

ios - SKAudioNode 崩溃 : AVAudioPlayerNode. mm:333:开始:所需条件为假:_engine->IsRunning()