How to delete the contents of a UITextField programmatically?

霸气de小男生 提交于 2019-12-31 06:59:20

问题


I am writing an iPhone app that has a number of UITextFields that requires the user to input a bunch of data. I would like to have a simple 'delete' facility that allows the user to discard any data they have put in to the multiple fields.

I've been struggling with this issue for a few days now. I can't seem to find a way of reaching into the individual text fields and changing the text. My app throws errors at me no matter what I try.


回答1:


There are several ways of tackling this.

You can write code to wipe each of them individually. To do this, you create an IBOutlet for each one, and assign a blank string to their text properties. If you only have a couple of fields, that's simplest. If you have more, it's not so good.

You can make them all children of a common container view and loop over its subviews. That way, you only need to hook up a single IBOutlet.

You can recurse over your entire view hierarchy and blank out all the text fields you find.

Another approach, which isn't very well documented by Apple, is to use an IBOutletCollection. That way, you can assign all of your text fields to the one IBOutletCollection and loop over it. This is probably the simplest, most straightforward way of doing it.




回答2:


You can just assign tags to each textfield in a sequence using tag property in interface builder and then get the textField like this

UITextField *txtf = (UITextField*)[self.view viewWithTag:aTagValue];

txtf.text = @""; or nil;


来源:https://stackoverflow.com/questions/6560888/how-to-delete-the-contents-of-a-uitextfield-programmatically

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