gpt4 book ai didi

cocoa - 如何重写方法的一小部分?

转载 作者:行者123 更新时间:2023-12-03 17:35:35 26 4
gpt4 key购买 nike

我现在在一个类中有这些方法,看起来工作得很好。我想创建一个继承这些方法的子类。我遇到的问题是,在第三种方法(shiftViewUpForKeyboard)中,我希望 if 语句是不同的 UITextField (镜像是当前示例)。我读过要重写子类中的方法,您基本上必须使用新编码完全复制它,但如果我只想更改那个小部分,最好的方法是什么?预先感谢您。

- (void) viewWillAppear:(BOOL)animated {

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(shiftViewUpForKeyboard:)
name: UIKeyboardWillShowNotification
object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(shiftViewDownAfterKeyboard)
name: UIKeyboardWillHideNotification
object: nil];


}

- (void) viewDidDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver: self
name: UIKeyboardWillShowNotification
object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: UIKeyboardWillHideNotification
object: nil];


}

- (void) shiftViewUpForKeyboard: (NSNotification*) theNotification;
{
if(mirror.isEditing == YES)
{

CGRect keyboardFrame;
NSDictionary* userInfo = theNotification.userInfo;
keyboardSlideDuration = [[userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] floatValue];
keyboardFrame = [[userInfo objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue];

UIInterfaceOrientation theStatusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];

if UIInterfaceOrientationIsLandscape(theStatusBarOrientation)
keyboardShiftAmount = keyboardFrame.size.width;
else
keyboardShiftAmount = keyboardFrame.size.height;

[UIView beginAnimations: @"ShiftUp" context: nil];
[UIView setAnimationDuration: keyboardSlideDuration];
self.view.center = CGPointMake( self.view.center.x, self.view.center.y - keyboardShiftAmount);
[UIView commitAnimations];
viewShiftedForKeyboard = TRUE;
}
}

最佳答案

无论如何,如果您不想复制子类中的完整方法并添加您的小自定义,我看到的唯一其他可能的方法是更改​​原始类。为此,我可以建议两种可能性:

1)您可以在原始类中创建一个名为的方法:

-(UITextField *)keyboardShiftTextField
然后在这个类中替换
mirror.isEditing
代码:

[[self keyboardShiftTextField] isEditing]

在这种情况下,两个类之间的唯一区别在于新方法的实现,对于原始类来说将是:

-(UITextField *)keyboardShiftTextField {
return mirror;
}
在子类中,这将返回正确的文本字段。

2)第二种方法更加优雅,因为它需要委托(delegate)模式的定义。这需要一些代码开销,但我们将为您提供更大的灵 active 。此外,如果创建子类的唯一原因只是重写第三个方法,那么使用委托(delegate)模式您可以完全避免创建子类,因为“自定义”工作将由委托(delegate)完成。如果要重写的方法数量超过一个,您仍然可以通过将所有需要自定义的部分移至协议(protocol)部分来使用此机制。对于 Obj-C 和 Cocoa 来说,这是一种非常常见的技术,这在许多情况下限制了对某些类的需求。通常,当您想要提供不同的功能时,您会使用子类,但在您的情况下,您并没有提供不同的功能,而只是对相同功能进行自定义( View 向上移动)。

关于cocoa - 如何重写方法的一小部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10367538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com