Iphone 如何从字符串指向对象
我的问题有点笼统;在我的项目中,我有10个Iphone 如何从字符串指向对象,iphone,objective-c,Iphone,Objective C,我的问题有点笼统;在我的项目中,我有10个UIButton对象 命名按钮1、按钮2、按钮3、按钮4、按钮5、按钮6、按钮7、按钮8、按钮9和按钮10 我还有UIImageview,它们的名称与从1到10的按钮完全相同 我想编写一个代码,通过按钮的最后一个字符(始终是1到10之间的数字)操作图像,并以相同的方式影响UIImageview 像这样的 buttonlastcharacter = i; if(sender.lastcharacternumber is:i){ Button
UIButton
对象
命名按钮1、按钮2、按钮3、按钮4、按钮5、按钮6、按钮7、按钮8、按钮9和按钮10
我还有UIImageview
,它们的名称与从1到10的按钮完全相同
我想编写一个代码,通过按钮的最后一个字符(始终是1到10之间的数字)操作图像,并以相同的方式影响UIImageview
像这样的
buttonlastcharacter = i;
if(sender.lastcharacternumber is:i){
Button%,i.frame = //Some manipulation
但基本上我只想通过字符串访问某个对象
我如何实现这样的行为?您可以这样做,
在IBAction方法中:
- (IBAction)click:(id)sender
{
UIButton *but = (UIButton *)sender;
but.frame = your manipulation code;
}
或者您可以检查标题,如:
if([but.currentTitle isEqualToString:@"Button1])
{
//Manipulate button 1
}
如果为1-10中的按钮添加了标签,则可以使用
if(but.tag == 2)
{
//Manipulate button 2
}
你可以这样做,
在IBAction方法中:
- (IBAction)click:(id)sender
{
UIButton *but = (UIButton *)sender;
but.frame = your manipulation code;
}
或者您可以检查标题,如:
if([but.currentTitle isEqualToString:@"Button1])
{
//Manipulate button 1
}
如果为1-10中的按钮添加了标签,则可以使用
if(but.tag == 2)
{
//Manipulate button 2
}
有两种更好的方法可以做到这一点。如果这些按钮都是静态的,并且在IB中,您可以使用IBCollection数组作为图像视图和按钮,通过匹配索引来简单地调用它们
更好的方法是只使用按钮或图像视图的标记值。有两种更好的方法可以做到这一点。如果这些按钮都是静态的,并且在IB中,您可以使用IBCollection数组作为图像视图和按钮,通过匹配索引来简单地调用它们
更好的做法是,只需为按钮或图像视图使用标记值。Hm,您可以为按钮使用数组,为UIImageView对象使用标记。它们都继承自UIView,它为您提供了一个.tag属性。它是NSInteger*型 为了方便起见,我建议将按钮命名为0到9。这并不重要,但是数组中的第一个索引将是0,因此相应地命名它们只会使事情变得更简单 定义
NSArray *buttonArray;
您可以选择NSMutableArray,这取决于您可能还想对它做什么
在viewDidLoad代码中:
buttonArray = [NSArray arrayWithCapacity:10];
buttonArray[0] = button0;
..
buttonArray[9] = button9;
在Interface Builder中的XIB文件中,或者在任何可以编程方式创建UIImages的地方,相应地添加标记
image0.tag = 0;
...
image0.tag = 9;
假设您将它们命名为image0到image9
在相应的操作方法代码中:
buttonArray[sender.tag] = someManipulation;
嗯,你可以为你的按钮使用一个数组,为你的UIImageView对象使用一个标签。它们都继承自UIView,它为您提供了一个.tag属性。它是NSInteger*型 为了方便起见,我建议将按钮命名为0到9。这并不重要,但是数组中的第一个索引将是0,因此相应地命名它们只会使事情变得更简单 定义
NSArray *buttonArray;
您可以选择NSMutableArray,这取决于您可能还想对它做什么
在viewDidLoad代码中:
buttonArray = [NSArray arrayWithCapacity:10];
buttonArray[0] = button0;
..
buttonArray[9] = button9;
在Interface Builder中的XIB文件中,或者在任何可以编程方式创建UIImages的地方,相应地添加标记
image0.tag = 0;
...
image0.tag = 9;
假设您将它们命名为image0到image9
在相应的操作方法代码中:
buttonArray[sender.tag] = someManipulation;
在您的情况下,这可能不是理想的解决方案,但您可以采用不同的方式: 使用kvo
UIButton* myButton = [self valueForKey:[NSString stringWithFormat:@"button%i",i]];
或者使用选择器和属性
UIButton* myButton = [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"button%i",i])];
在您的情况下,这可能不是理想的解决方案,但您可以采用不同的方式: 使用kvo
UIButton* myButton = [self valueForKey:[NSString stringWithFormat:@"button%i",i]];
或者使用选择器和属性
UIButton* myButton = [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"button%i",i])];