ios - 在不同的 IBAction 中更改以编程方式创建的 UIButton 的属性

标签 ios uibutton

我有一种方法可以创建多个 UIButton以编程方式创建实例并将它们定位在 View 中。另一个IBAction需要更改其中一个的背景颜色 UIButton但是当我尝试操作它时被解雇时,它告诉我在 UIView * 类型的对象上找不到属性

按钮是使用以下方法创建的:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];

当我尝试从其他 IBAction 访问它时,例如:

button.backgroundColor = [UIColor blackColor];

它因上述错误而失败。

非常感谢任何帮助。我看到另一个建议创建一个数组作为 IBOutlet 的答案并以这种方式访问​​它,但我想知道是否还有其他方式。

谢谢!

最佳答案

在全局声明这个button并在tag中标识每个按钮,就像或假设这个

 UIButton * button, *button2; // declare in your view controller.h

 - (IBAction)butaction:(id)sender;    //this is your color change method;

在你的 view controller.m 中你添加这个按钮的地方

 button = [UIButton buttonWithType:UIButtonTypeCustom];
 button.tag=10;   //this is important
 [self.view addSubview:button];

  button1 = [UIButton buttonWithType:UIButtonTypeCustom];
  button1.tag=20;   //this is important
 [self.view addSubview:button1];


  //here ur color change method

     - (IBAction) butaction:(UIButton*)sender {


     switch (sender.tag)
      {
       case 10:
         [button setBackgroundColor:[UIColor blackColor]];

       break;

        case 20:
            [button1 setBackgroundColor:[UIColor blackColor]];
          break;

       default:
        break;

           }
        }

关于ios - 在不同的 IBAction 中更改以编程方式创建的 UIButton 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009178/

相关文章:

ios - 添加元素到搜索历史记录?

iOS 应用程序图像大小和命名约定

ios - Sprite-Kit colorizeWithColor 没有将 Sprite 与正确的颜色混合

ios - iOS-UIButton文本左对齐等于另一个UIButton包含图像的文本

ios - 在 UIButton 中,setImage 和 setBackgroudnImage content id 不同,它旋转了 90 度

ios - 如何在 App Store 应用程序的标签栏中同时使用实体和轮廓图标?

ios - Swift - 在后台推送 CollectionView

ios - 从 subview 调用 super View 函数

ios - 不同的图像取决于用户屏幕尺寸

swift - 当我点击 UIButton 时图像不会改变