how I should send data from xib to viewcontroller?

半世苍凉 提交于 2021-02-11 12:47:16

问题


i have a view that is a xib, this view contains a buttons for a calculator, I did this because I need a custom keyboard for my app, my app has some views that needs this keyboard the problem is, how I send the data from view to my view controller? in my view controller I only has a textfield and a view with xib custom class

I use swift 4.2

custom view and textflied

this is my code from my xib

import UIKit

class keyboardView: UIView {


@IBOutlet var viewKeyboard: UIView!

var textIntroduced = ""

override init(frame: CGRect) { // for using CustomView in code
    super.init(frame: frame)
    custom()
}

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

private func custom()
{
    Bundle.main.loadNibNamed("keyboard", owner: self, options: nil)

    viewKeyboard.frame = self.bounds
    viewKeyboard.autoresizingMask = [.flexibleHeight,.flexibleWidth]
    for view in viewKeyboard.subviews
    {
        view.isExclusiveTouch = true
    }
    addSubview(viewKeyboard)
}

@IBAction func addOne(_ sender: Any) {
    textIntroduced += "1"
}
@IBAction func addTwo(_ sender: Any) {
    textIntroduced += "2"
}
@IBAction func addThree(_ sender: Any) {
    textIntroduced += "3"
}
@IBAction func addFour(_ sender: Any) {
    textIntroduced += "4"
}
@IBAction func addFive(_ sender: Any) {
    textIntroduced += "5"
}
@IBAction func addSix(_ sender: Any) {
    textIntroduced += "6"
}
@IBAction func addSeven(_ sender: Any) {
    textIntroduced += "7"
}
@IBAction func addEight(_ sender: Any) {
    textIntroduced += "8"
}
@IBAction func addNine(_ sender: Any) {
    textIntroduced += "9"
}
@IBAction func addZero(_ sender: Any) {
    textIntroduced += "0"
    print(textIntroduced)
}
@IBAction func removeNumber(_ sender: Any) {
    textIntroduced.removeLast()
}
}

in my view controller I only has a textfield and view with custom class

i want to push any button view and the result should be written in the textfield.


回答1:


You can use protocol to observe data changes in your xib. First of all you need to create a protocol like this.

protocol NumberCalculable: class {
    func addNumber(_ number: Int)
}

Then, inside your xib file below your viewKeyboard outlet you need to create a delegate for your protocol.

weak var delegate: NumberCalculable?

Instead of doing textIntroduced += 1 you should change with this delegate?.addNumber(1) and same for other IBAction methods. Thirdly, you need to conform your protocol in your viewController class doing keyboardView.delegate = self inside viewDidLoad() method.

extension ViewController: NumberCalculable {
func addNumber(_ number: Int) {
// do whatever you want
}
}

Hope this helps.



来源:https://stackoverflow.com/questions/56745713/how-i-should-send-data-from-xib-to-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!