使用控件名称作为字符串转换为控件 [英] Cast to a control using the control name as a string

查看:85
本文介绍了使用控件名称作为字符串转换为控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的XIB中有几个文本字段(和标签),在我的应用程序的某个时刻,我构建了一个包含控件名称(即其中一个文本字段)的字符串。
如何使用我创建的包含文本字段名称的字符串来引用实际的文本字段。

I have several textfields (and labels) in my XIB and at some point in my application I build dynamicaly a string which contains a control name (i.e. one of the textfields). How can I refer to the actual textfield using the string I created that holds the name of the textfield.

例如,我有txt1,txt2,txt3 ,txt4为UITextFields
,我有一个字符串(str),其中包含名称之上的一个字段(str =txt3)
然后我想更改uitextfield txt3的内容,因为str有 txt3此时

For example, I have txt1 , txt2, txt3, txt4 as UITextFields and i have a string (str) that contains one of the fields above names (str ="txt3") then i want to change the content of the uitextfield txt3 since str have "txt3" at this point.

如何从字符串转换为实际控件?

How do I cast from the string to the actual control?

推荐答案

如果 UITextField 都有后备属性,那么你可以使用KVC来获取对控件的引用,然后你就可以了正常使用它。

If the UITextFields all have a backing property then you can use KVC to get a reference to the control and then you just use it as normal.

NSString *str = @"txt1";
UITextField *myTextField = [self valueForKey:str];
myTextField.text = @"what ever you want to update to";



附注



虽然你还没有提到 str的来源 @JefferyThomas提出了一个非常有效的观点,即不信任尚未验证的使用输入。

Side note

Although you have not mentioned the source of str @JefferyThomas raises a very valid point about not trusting use input that has not been validated.

这篇关于使用控件名称作为字符串转换为控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆