未调用子类覆盖方法 [英] subclass override method not being called

查看:88
本文介绍了未调用子类覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 UITextField 的子类来覆盖方法 rightViewRectForBounds.

I created a subclass of UITextField to override the method rightViewRectForBounds.

这是我的自定义类 CustomTextField

Here is my custom class 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.

Now I set up my ViewController to call the custom class instead of 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 应该调用我的方法覆盖:正确的叠加视图放置在由 rightViewRectForBounds: 方法返回的矩形中".为什么我的覆盖不起作用?

The property rightView should call my method override according to Apple's Documentation: "The right overlay view is placed in the rectangle returned by the rightViewRectForBounds: method of the receiver". Why isn't my override working?

对不起,如果这是一个不好的问题.我只编程了一个月.

Sorry if this is a bad question. I've only been programming for a month.

推荐答案

问题很可能是 field1 实际上不是 CustomTextField.使用断点或一些日志记录很容易确认这一点.

The problem is most likely that field1 is not in fact a CustomTextField. It is easy to confirm this with a breakpoint or some logging.

记住,仅仅声明某物的类是不够的.那个东西实际上必须那个类(多态).一个实例一个类,完全不用考虑如何转换或声明一个引用它的变量.

Remember, it is not enough to declare the class of something. That thing must actually be that class (polymorphism). An instance has a class, quite without regard for how you may cast or declare a variable that refers to it.

这篇关于未调用子类覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆