我创建了 UITextField 的子类来重写 rightViewRectForBounds 方法。
这是我的自定义类 CustomTextField
@interface CustomTextField : UITextField
@end
@implementation CustomTextField
// override rightViewRectForBounds method:
- (CGRect)rightViewRectForBounds:(CGRect)bounds{
NSLog(@"rightViewRectForBounds");
CGRect rightBounds = CGRectMake(bounds.origin.x + 10, 0, 30, 44);
return rightBounds ;
}
@end
现在我将 ViewController 设置为调用自定义类而不是 UITextField。
#import "OutputViewController.h"
#import "CustomTextField.h"
@interface OutputViewController () <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet CustomTextField *field1;
@property (strong, nonatomic) IBOutlet UILabel *label1;
- (void)methodName
{
self.field1.rightView = self.label1;
}
根据Apple的文档,属性rightView应该调用我的方法重写:“右覆盖 View 放置在由接收者的rightViewRectForBounds:方法返回的矩形中”。为什么我的覆盖不起作用?
很抱歉,如果这是一个糟糕的问题。我才编程一个月。
最佳答案
问题很可能是 field1
实际上不是 CustomTextField。通过断点或一些日志记录可以很容易地确认这一点。
请记住,仅仅声明某物的类别是不够的。那个东西实际上必须是 那个类(多态性)。一个实例有一个类,完全不用考虑如何转换或声明引用它的变量。
关于ios - 未调用子类覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748450/