iOS集成Material Design时MDCTextInputControllerUnderline未检测到问题求助
Hey there! I’ve run into this exact snag before when working with Material Components for iOS, so let’s walk through the most common fixes to get MDCTextInputControllerUnderline working for you.
1. Double-Check Your Dependencies & Imports
First, make sure you’ve got the right components set up correctly:
- If you’re using CocoaPods, confirm your
Podfileincludes the TextFields module:
Runpod 'MaterialComponents/TextFields'pod installorpod updateto pull in the latest compatible version. - In your Swift file, import the explicit module to ensure the controller is recognized:
(For Objective-C projects, addimport MaterialComponents.MaterialTextFields#import "MaterialComponents/MaterialTextFields.h"to your bridging header.)
2. Properly Link MDCTextField to MDCTextInputControllerUnderline
Your current code creates an MDCTextField, but you haven’t connected it to an MDCTextInputControllerUnderline instance—this is mandatory to enable the underline styling. Here’s how to fix your code:
class ViewController: UIViewController { let userNameTextField: MDCTextField = { let textField = MDCTextField() textField.placeholder = "Full Name" // Disable autoresizing mask so Auto Layout works textField.translatesAutoresizingMaskIntoConstraints = false return textField }() // Declare the controller instance to hold the underline configuration private var userNameInputController: MDCTextInputControllerUnderline! override func viewDidLoad() { super.viewDidLoad() view.addSubview(userNameTextField) // Initialize the underline controller and link it to your text field userNameInputController = MDCTextInputControllerUnderline(textInput: userNameTextField) // Fix your Auto Layout constraints (note the corrected "anchor" spelling) NSLayoutConstraint.activate([ userNameTextField.topAnchor.constraint(equalTo: signUpButton.bottomAnchor, constant: 20), userNameTextField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16), userNameTextField.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16), userNameTextField.heightAnchor.constraint(equalToConstant: 48) ]) } }
3. Fix Common Code Typos & Oversights
I spotted a couple of small issues in your original snippet that might cause unexpected errors:
- You named your text field
userNameTextFieldbut tried to addm_userNameTextFieldto the view—make sure variable names match consistently. acnchoris a typo; it should beanchor.- Always set
translatesAutoresizingMaskIntoConstraints = falsewhen using programmatic Auto Layout to avoid conflicts.
4. Verify Version Compatibility
If you’re still stuck, ensure your Material Components version aligns with your target iOS version. The latest releases support iOS 13+, so if you’re targeting an older OS, specify a compatible version in your Podfile (e.g., pod 'MaterialComponents/TextFields', '~> 120.0').
内容的提问来源于stack exchange,提问作者M Nur Firdaus Izrullah

