问题
I am trying to generate UITextField dynamically in place of UILabel. Now i want to update that data. I am displaying data in the UILabel from the database and there is an UIButton for editing. When i click on that UIButton UITextField should be generated in place of UILabel and also data should be displayed in UITextField.
回答1:
What you can do is to design a view with all textfield which works in two modes, first readonly (by setting userInteraction to false ) and second editing mode. This way you can avoid the use of labels. This will need only one edit button for all of the fields. if you still want to stick with your approach, you can hide the labels, use their frames to create textfields at their place and make them visible as long as you are working in edit mode. Don't forget to use
[self.view bringSubviewToFront:TEXT_FIELD];
While you add them to your view. e Managing the editing with the approach I mentioned earlier is mor easy and require less efforts. Hope it helps
回答2:
you need to implement this textField in .h file, to get access to it when you finish aditing. Then, in your button callback:
textField = [[UITextField alloc] initWithFrame:[yourUILabel frame]];
[textField setText:yourUILabel.text];
[self.view addSubView:textField];
then, to replace it back:
[yourUILabel setText:textField.text];
[textField removeFromSuperView];
回答3:
You can use the methods that others have described here but it sounds like you just want a UITextField that looks like a label and you want to control whether or not it's editable.
- set enabled to YES / NO depending on whether you want the user to edit the UITextField
- set the borderStyle of a UITextField (usually between UITextBorderStyleRoundedRect and UITextBorderStyleNone)
You can then toggle the enabled and borderStyle values as follows: - on initial view: enabled: NO, border style: UITextBorderStyleNone - on button tap: enabled: YES, border style: UITextBorderStyleRoundedRect
You don't have to mess with the view hierarchy and worry about frames, etc, this way.
来源:https://stackoverflow.com/questions/8207230/unable-to-generate-uitextfield-dynamically-in-place-of-uilabel