ios - 在自定义 View 和 View Controller 之间传递数据

标签 ios swift uiview uiviewcontroller uicontrol

我有一个自定义 UIControl (TestControl),并且想要将一个简单的字符串传递到主视图上的标签。 UIControl (TestControl) 位于 UIView (CustomView) 内,该 UIView (CustomView) 已使用具有自定义类 (CustomView) 的 View 放置在 Storyboard 上。

有什么简单的实现可以解决这个问题?

我注意到 CustomView 在 ViewController 中的 viewDidLoad() 之前被调用。

ViewController.swift

import UIKit

@IBOutlet var someLabel: UILabel!

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

} 

TestControl.swift

import UIKit

class TestControl: UIControl {

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

        self.backgroundColor = UIColor.blackColor()

    //this is where it would be good if a string could be passed to a label

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

自定义 View .swift

import UIKit

@IBDesignable class CustomView: UIView{

    #if TARGET_INTERFACE_BUILDER
    override func willMoveToSuperview(newSuperview: UIView?) {

      let testing: TestControl = TestControl(frame: self.bounds)
      self.addSubview(testing)

    }

    #else
    override func awakeFromNib() {

        super.awakeFromNib()

        let testing: TestControl = TestControl(frame: self.bounds)
        self.addSubview(testing)

    }
    #endif
}

enter image description here

最佳答案

由于 Storyboard中有一个控件,因此您所要做的就是将 didChange 事件处理程序连接到 View Controller 中的 IBAction 。然后,它可以解释此操作以执行您想要的操作。

关于ios - 在自定义 View 和 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063221/

相关文章:

ios - 在最大长度上更改 UITextField 响应程序

ios - 将数据从一个 TableView 传递到另一个 TableView

ios 在 subview 中自动调整 uilabel 大小

ios - 无法将 UITableView 添加到 UIView swift

ios - CupertinoTextField 中的 Flutter 文本验证

ios - 为什么ios系统的声音在模拟器中播放不了?

ios - 适用于 iOS 12.1 的 flutter : black screen instead of an app

android - 如何在 TextField 获得焦点时滚动到 SingleChildScrollView 的底部?

swift - 如何在不进入应用程序的情况下从快速操作菜单复制到 UIPasteBoard?

ios - 动态创建的 UIView 在碰撞后不会动画