2

我有一个委托方法,其中只有一些代码,在输入的数字的末尾放置一个 % 符号。

- (void)textFieldDidEndEditing:(UITextField *)UItextfield {
     NSString *oldTextFieldValue = UItextfield.text;
     UItextfield.text = [NSString stringWithFormat:@"%@ %%",oldTextFieldValue];
   }

我可以不这样做,而是采取以下行动

-(IBAction)Calculate:(UITextField *)UITextfield;
{
    NSString *oldTextFieldValue = UItextfield.text;
    UItextfield.text = [NSString stringWithFormat:@"%@ %%",oldTextFieldValue];
}

然后在 Delegate 函数中调用那个动作?就像是

-(void)textFieldDidEndEditing:(UITextField *)UItextfield {
[self Calculate:self]
}

我试过了,它不起作用。我知道它会让我得到相同的结果,但我只想知道它是否可以完成。我想我在问是否可以在另一种方法(textFieldDidEndEditing)中调用方法(Calculate)以及如何调用。

4

2 回答 2

4

您提供self的方法参数是您所在的类的实例。在这种情况下这是错误的,因为方法参数应该是UITextField. 试试[self Calculate:UItextfield]你的方法。

于 2012-12-22T18:46:53.300 回答
2

在大多数编程语言中,从方法调用其他方法一直都在发生。这是一种无需复制/粘贴即可拆分代码并在不同位置重用代码的好方法。

(这对你来说可能太基础了。在那种情况下很抱歉)

如果您也使用标准命名约定,事情可能更容易理解。('likeThis' 用于变量和方法名;'LikeThis' 用于类名)

- (void)textFieldDidEndEditing:(UITextField *)textField {
     NSString *oldTextFieldValue = textField.text;
     textField.text = [NSString stringWithFormat:@"%@ %%",oldTextFieldValue];
}

textField这里,是指向刚刚完成编辑的 UITextField 对象的指针。您想将此对象传递给您的新“其他”方法。

[self calculate:textField];

self是指向当前类的实例的指针。例如,在名为“MyViewController”的 UIViewController 子类中,self 指的是此类的当前实例。由于该-calculate方法是实例方法(以“-”开头),因此需要您使用self. 变量textField在冒号之后传递。

- (void)calculate: (UITextField*)textField {
NSString *oldTextFieldValue = textField.text;
textField.text = [NSString stringWithFormat:@"%@ %%",oldTextFieldValue];

}

IBAction当您希望从 xib 或故事板中的 UIComponent 调用方法时,仅使用关键字。

于 2012-12-22T19:30:30.380 回答