我有一个自定义的UIControl(TestControl),并希望将一个简单的字符串传递给主视图上的标签。 UIControl(TestControl)位于UIView(CustomView)内部,该视图已使用具有自定义类(CustomView)的视图放置在故事板上。
什么是一个可以解决这个问题的简单实现?
我注意到在ViewController中的viewDidLoad()之前调用了CustomView。
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")
}
}
CustomView.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
}
答案 0 :(得分:0)
由于您在故事板中有控件,所以您应该做的就是将didChange
事件处理程序连接到视图控制器中的IBAction
。然后,这可以解释此操作以执行您想要的操作。