Swift:如何在ViewController中跨XIB文件访问IBOutlet并实现交互
Hey there! Since you're new to Swift, let's break this down simply. The main issue right now is that your addUIView2 is a local variable inside viewDidLoad—so your button action method can't access it. Here's how to fix this step by step:
Step 1: Add properties for your XIB views to the ViewController
First, declare two properties at the top of your ViewController class, so they're accessible throughout the class:
class ViewController: UIViewController { // Properties to hold references to your XIB-based views private var totalOzView: totalOZVC? private var glassSelectorView: GlassSelectorVC? // Rest of your class code... }
Step 2: Update viewDidLoad to assign these properties
Modify your viewDidLoad method to store the loaded XIB views in the class properties instead of using local variables:
override func viewDidLoad() { super.viewDidLoad() // Load and configure totalOz view if let loadedTotalOzView = Bundle.main.loadNibNamed("totalOz", owner: self, options: nil)?.first as? totalOZVC { totalOzView = loadedTotalOzView self.view.addSubview(loadedTotalOzView) // Attach button action loadedTotalOzView.button120ml.addTarget(self, action: #selector(buttonSelectGlassSize(sender:)), for: .touchUpInside) } // Load and configure GlassSelector view if let loadedGlassSelectorView = Bundle.main.loadNibNamed("GlassSelector", owner: self, options: nil)?.first as? GlassSelectorVC { glassSelectorView = loadedGlassSelectorView self.view.addSubview(loadedGlassSelectorView) loadedGlassSelectorView.labelGlassSelect.textColor = .white loadedGlassSelectorView.labelGlassSelect.text = "Select the size of Glass" } }
Step 3: Update the button action to modify the label
Now you can access the glassSelectorView property in your button action method to update the label's text:
@objc func buttonSelectGlassSize(sender: UIButton) { // Change the label text when the button is tapped glassSelectorView?.labelGlassSelect.text = "120mL Glass Selected!" }
Quick Checks to Avoid Issues:
- Double-check that in your
totalOZVCXIB file, the button is properly connected to thebutton120mloutlet (Ctrl-drag from button to the code). - Make sure
GlassSelectorVC's XIB has the label connected tolabelGlassSelectoutlet the same way. - The optional (
?) on our properties and in the button action is safe—it prevents crashes if the XIB fails to load for any reason.
内容的提问来源于stack exchange,提问作者Saad Sikandar
相关产品推荐
相关产品推荐

