简体   繁体   English

将 NSString 转换为 UIButton 类型

[英]Cast NSString to UIButton type

Im trying to cast a string to a button type.我试图将字符串转换为按钮类型。 Basically, Im looping through, say 5 buttons, named btn1,btn2..btn5.基本上,我遍历了 5 个按钮,名为 btn1,btn2..btn5。 Here's the snippet:这是片段:

- (IBAction)replaceImg
{
  UIButton* b;
  for(int i=0; i<5; i++)
    {       
    b = (UIButton*)[NSString stringWithFormat:@"btn%d",i]; //1!
    if([b isHighlighted])
      {
      int imgNo = (arc4random() % 6) + 1;
      UIImage *img = [UIImage imageNamed:[NSStringstringWithFormat:@"%d.png", imgNo]];
      [b setImage:img forState:(UIControlState)UIControlStateNormal];
      }
    }
}

The line marked 1 is giving a problem, if I swap it with b = btn1, it works perfectly.标记为 1 的行有问题,如果我将它与 b = btn1 交换,它可以完美运行。 Please help.请帮忙。 I couldnt find a way to access a button by its name either.我也找不到按名称访问按钮的方法。 Like UIImage has something like imageNamed.像 UIImage 有类似 imageNamed 的东西。

you can't cast NSString to UIButton because both are completely different type.您不能将NSString转换为UIButton因为两者都是完全不同的类型。

Use tag property of UIView to assign and unique number to each UIButton and at any point of time you could access them by using viewWithTag .使用UIButton标签属性为每个UIView分配唯一编号,您可以在任何时候使用viewWithTag访问它们。

You can't 'cast' an NSString to a button.你不能将一个 NSString 'cast' 到一个按钮上。 To get specific buttons, or buttons by name, depends on how you created them.要获取特定按钮或按名称获取按钮,取决于您创建它们的方式。 Store your created buttons into an array, or if they come from a NIB then gather their pointers into an array, then loop through the array of button pointers.将您创建的按钮存储到一个数组中,或者如果它们来自 NIB,则将它们的指针收集到一个数组中,然后循环遍历按钮指针数组。 Controls are also UIViews, so you can assign a numeric 'tag' to each button in Interface Builder then use UIView's viewWithTag: method to search for a specific view with a specific tag.控件也是 UIView,因此您可以为 Interface Builder 中的每个按钮分配一个数字“标签”,然后使用 UIView 的 viewWithTag: 方法来搜索具有特定标签的特定视图。

An NSString isn't a UIButton , so casting it to one isn't going to work. NSString不是UIButton ,因此将其转换为一个是行不通的。 Well, it might work as far as syntax goes, but logic-wise, it will fail.好吧,就语法而言,它可能会起作用,但从逻辑上讲,它会失败。 You simply cannot interact with an NSString the same way you can a UIButton .您根本无法像与UIButton一样与NSString进行交互。 If you need to find your button by name, then you can either retain pointers to those buttons (either in an array, a map, or just as plain instance variables, to name a few ways), or you could alternatively use something like viewWithTag: .如果您需要按名称查找按钮,则可以保留指向这些按钮的指针(在数组中,map,或仅作为普通实例变量,仅举几例),或者您也可以使用类似viewWithTag: .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM