iOS 中 UIButton 的简单子类化



我想我已经遵循了示例代码,但下面给了我一个错误。

我想对UIButton进行子类化并添加几个属性,但我从一开始就失败了。

我创建了一个子类文件。 这些是我的 .h/.m:

// damButton.h
#import <UIKit/UIKit.h>
@interface damButton : UIButton
{
    CGFloat _position;
}
@property (nonatomic) CGFloat position;
@end

// damButton.m
#import "damButton.h"
@implementation damButton
@synthesize position = _position;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
@end

在我的主视图控制器中,我已经导入了我的自定义按钮,但是当我使用该属性的内置 getter 和 setter 时,我收到一个错误:

//MainViewController.m
#import "damButton.h"
// then within a method...
damButton *b = [damButton buttonWithType:UIButtonTypeRoundedRect];
[b position:5.0];

生成此错误:No visible @interface for 'damButton' declares the selector 'position:'

不确定我在这里错过了什么,我几乎逐字复制了它(我认为)。我只想使用内置的getter/setter(目前)。

我错过了什么?

你正在调用getter方法,而不是setter方法-setPosition,即try:

[b setPosition:5.0];

b.position = 5.0;

请问您想通过子类化UIButton来实现什么?

最新更新