我正在尝试扩展UIButton类以添加一些方法,但是当我尝试初始化对象时遇到了一些问题。
-(id)init{
UIImage* image = [UIImage imageNamed:@"button_background.png"];
CGRect frame= CGRectMake(100.0, 70.0, 45.0 ,45.0);
self.frame = frame;
[self setTitle:@"title" forState:UIControlStateNormal];
[self setBackgroundImage:image forState:UIControlStateNormal];
[self setImage:image forState:UIControlStateNormal];
NSLog(@"type: %d",self.buttonType);
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f",frame.origin.x, frame.origin.y ,frame.size.width, frame.size.height);
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f",self.frame.origin.x, self.frame.origin.y ,self.frame.size.width, self.frame.size.height);
if(self != nil){
//
}
return self;
}
接缝工作正常,执行期间没有警告或错误。 但是在控制台中出现了frame和self.frame的值之间的一些不一致,当然按钮不会出现在屏幕上。
type: 0
x: 100.000000
y: 70.000000
width: 45.000000
height: 45.000000
x: 0.000000
y: 0.000000
width: 0.000000
height: -1.998576
请帮助我,我已经忘记了! :\
答案 0 :(得分:1)
当你在Objective-C中进行子类化时,你必须(1)覆盖指定的初始化器(2)调用超类的指定初始化器。你没有。
你应该这样做:
/**
* \brief Convenience class method to replace button method of UIButton
*/
+(id)myButton
{
MyButton* myButton = [[MyButton alloc]
initWithFrame:CGMakeRect(100.0, 70.0, 45.0, 45.0)];
return [myButton autorelaase];
}
-(id)initWithFrame:(CGRect)f
{
if(self = [super initWithFrame:f])
{
UIImage* image = [UIImage imageNamed:@"button_background.png"];
[self setTitle:@"title" forState:UIControlStateNormal];
[self setBackgroundImage:image forState:UIControlStateNormal];
[self setImage:image forState:UIControlStateNormal];
NSLog(@"type: %d",self.buttonType);
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f", NSStringFromCGRect(frame));
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f", NSStringFromCGRect(self.frame));
}
return self;
}
希望这会有所帮助。如果您需要更多信息,请告诉我。
答案 1 :(得分:0)
在您记录的那一刻,您没有将按钮添加到任何视图。 无论如何,代码必须看起来像这样吗?
-(id)init{
if(self != nil){
UIImage* image = [UIImage imageNamed:@"button_background.png"];
CGRect frame= CGRectMake(100.0, 70.0, 45.0 ,45.0);
self.frame = frame;
[self setTitle:@"title" forState:UIControlStateNormal];
[self setBackgroundImage:image forState:UIControlStateNormal];
[self setImage:image forState:UIControlStateNormal];
NSLog(@"type: %d",self.buttonType);
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f",frame.origin.x, frame.origin.y ,frame.size.width, frame.size.height);
NSLog(@"x: %f\ny: %f\nwidth: %f\nheight: %f",self.frame.origin.x, self.frame.origin.y ,self.frame.size.width, self.frame.size.height);
}
return self;
顺便问一下,你不要忘记调用超类init吗?
答案 2 :(得分:0)
我刚才回答了一个非常相似的问题: How to create a very custom uibutton like UITableViewCellStyleSubtitle in iOS
像其他人一样指出,UIButton是一个类集群,所以你可能不想将它子类化。但是,您可能会发现创建UIButton类别更容易,而不是子类化UIControl。