English 中文(简体)
将NSString强制转换为UIButton类型
原标题:Cast NSString to UIButton type

我正在尝试将字符串转换为按钮类型。基本上,我循环通过5个按钮,命名为btn1,btn2…btn5。以下是片段:

- (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. Please help! I couldnt find a way to access a button by its name either. Like UIImage has something like imageNamed.

问题回答

您不能将NSString强制转换为UIButton,因为两者的类型完全不同。

使用UIViewtag属性为每个UI按钮分配一个唯一的编号,您可以在任何时候使用viewWithTag访问它们。

不能将NSString强制转换为按钮。要获取特定按钮,或按名称获取按钮,取决于创建它们的方式。将创建的按钮存储到一个数组中,或者如果它们来自NIB,则将它们的指针收集到一个阵列中,然后在按钮指针数组中循环。控件也是UIView,因此您可以在界面生成器中为每个按钮分配一个数字标记,然后使用UIView的viewWithTag:方法搜索具有特定标记的特定视图。

NSString不是UIButton,因此将其强制转换为一个是行不通的。好吧,它可能会像语法那样工作,但从逻辑上讲,它会失败。您根本无法像使用UIButton那样与NSString进行交互。如果您需要按名称查找按钮,那么您可以保留指向这些按钮的指针(可以在数组、映射中,也可以仅作为简单的实例变量,举几个例子),也可以使用类似于viewWithTag:





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

Iphone NSTimer Issue

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the ...

Include a .txt file in a .h in C++?

I have a number of places where I need to re-use some template code. Many classes need these items In a .h could I do something like: #include <xxx.txt> and place all of this code in the ....

Iterating over string/strlen with umlauted characters

This is a follow-up to my previous question . I succeeded in implementing the algorithm for checking umlauted characters. The next problem comes from iterating over all characters in a string. I do ...

Xcode open two editor windows with same file

Is it possible to open the same file in two separate windows in Xcode. I can open a file in one window and the same file in the main Xcode editor window, but I wanted two separate fulltime editor ...

Forcing code signing refresh in Xcode

In our environment, we share resources across multiple projects and platforms. When building for iPhone, only a subset of those resources are needed. Since that subset is still considerable, we have ...

热门标签