【问题标题】:Reusing variables in other method file在其他方法文件中重用变量
【发布时间】:2015-09-20 08:00:21
【问题描述】:

我有以下代码从名为 FirstViewController 的方法文件生成 UIBUtton,因为按钮的位置会在不同的 secondviewController 或 thirdViewController 中改变,是否可以为 unbutton 的位置(CGRect)设置一个变量FirstViewController 并更改第二个或第三个 viewController 中的 CGRect 值?

在 FirstViewController.m 中

     -(void)method:(UIView *)_view {

            UIButton*Touch1= [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [Touch1 addTarget:self action:@selector(TouchButton1:) forControlEvents:UIControlEventTouchUpInside];
            [Touch1 setFrame:CGRectMake(50,50, 100, 100)];
            **//I want to set a variable for the CGRectMake**
            Touch1.translatesAutoresizingMaskIntoConstraints = YES;
            [Touch1 setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
            [Touch1 setExclusiveTouch:YES];
             [_view addSubview:Touch1];

            NSLog(@"test ");
        }

在 SecondViewController.m 中

- (void)viewDidLoad {
    [super viewDidLoad];

    ViewController * ViewCon = [[ViewController alloc]init];
    **//Change variable here by defining the new CGRect here.**
    [ViewCon method:self.view];
}

【问题讨论】:

  • 您是否有理由不将您想要的CGRect 值作为第二个参数传递给method:? (并将该方法的名称更改为更具描述性的名称,例如makeButtonInView:withFrame:

标签: ios objective-c xcode variables uibutton


【解决方案1】:

此模式不正确:

ViewController * ViewCon = [[ViewController alloc]init];
[ViewCon method:self.view];

当你分配一个新的视图控制器只是为了使用它的方法之一,然后你把视图控制器实例扔掉了。这是非常低效和不方便的。

要么将方法移动到实用程序类,作为类方法:

[Utils method:self.view rect:rect];

或子类UIViewController 并在该基类中实现该方法,然后从该基类派生所有类似的视图控制器,并将任何变量传递给它。

[self method:rect];      // method implemented in MyBaseViewController

您还问过这个question before 并接受了一个提倡使用这种不良模式的答案。这会误导其他人使用这种糟糕的模式。

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多