【问题标题】:Objective-C - Accessing property from different class [duplicate]Objective-C - 从不同的类访问属性[重复]
【发布时间】:2013-05-23 11:25:42
【问题描述】:

所以在我的VC1.h 中我得到了:

@property (weak, nonatomic) IBOutlet UIButton *monthly;

这连接到视图上的按钮,该按钮连接到VC1 类。 如何在不同的类中访问此按钮的 .enabled 属性?

编辑:

我有一个连接到 tableview 的类。在表格视图中选择特定行时,我想禁用主类中的按钮。我只需要知道如何获取按钮的当前状态并在另一个类中禁用它。

IBaction 来自按钮:

- (IBAction)monthly:(id)sender {
[monthly setSelected:YES];
yearly.enabled = YES;

if([monthly isSelected])
{
    NSLog(@"monthly ON");
    [yearly setSelected:NO];
    monthly.enabled = NO;

    _dateSpecifiedYearButton.hidden = TRUE;
    _dateSpecifiedYearButton.enabled = NO;
    _dateSpecifiedButton.hidden = FALSE;
    _dateSpecifiedButton.enabled = YES;
}

}

Tableview.m:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

[popoverSpending dismissPopoverAnimated:YES];

UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
if([self.delegate respondsToSelector:@selector(spendingButtonText:)]) {
    [self.delegate spendingButtonText:cell.textLabel.text];
}

if (indexPath.row == 2) {
    NSLog(@"2");

    ViewController *vc = [[ViewController alloc] init];
    if (vc.monthly.enabled)
    {
        vc.monthly.enabled = NO;
        vc.yearly.enabled = NO;           
    }
}

[self dismissViewControllerAnimated:YES completion:nil];
}

以上是可能对这个问题很重要的代码部分。

【问题讨论】:

  • (instance of VC1).monthly.enabled?访问属性并没有什么神奇之处。
  • VC1 和 VC2 是如何关联的?
  • @mAu 好吧,我似乎无法弄清楚。你的建议对我没有帮助。
  • 你的问题是你如何实例化 vc - 只是做一个 alloc init 会创建一个与你在屏幕上的实例不同的实例。你需要说明你是如何从 ViewController 到带有 table view 的控制器的。这两个控制器之间的关系对于回答您的问题很重要。

标签: ios objective-c


【解决方案1】:
VC1 *vc = [[VC1 alloc] init];//Allocate VC1 in appDelegate, if you allocate VC1 in VC2, then it allocates new instance. 


AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (app.vc.monthly.enabled)//chk button state
{
}

【讨论】:

  • 感谢您的解释。似乎我可以通过这种方式访问​​属性,但是我的按钮状态并没有改变。 ViewController *vc = [[ViewController alloc] init]; if (vc.monthly.enabled) { vc.monthly.enabled = NO; vc.yearly.enabled = 否; }
  • @Tarayaa chk 我的更新答案。
  • 我需要在一个类的 didSelectRow 方法中访问启用状态。所以启用的检查不能在 appDelegate 中。我应该在我的 appdelegate 哪里分配它?
  • 在 appDelegate 中只分配 VC1。通过在表 didSelectRow 方法中创建 appdelegate 实例来检查按钮状态。
  • 那么你应该明确表达你的目标是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2011-09-05
相关资源
最近更新 更多