gpt4 book ai didi

iOS 编程 : Problem extending UIButton class

转载 作者:行者123 更新时间:2023-11-29 05:04:01 24 4
gpt4 key购买 nike

我正在尝试扩展 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

请帮帮我,我快疯了! :\

最佳答案

当您在 Objective-C 中进行子类化时,您必须 (1) 覆盖指定的初始值设定项 (2) 调用父类(super class)的指定初始值设定项。你两者都不做。

你应该做这样的事情:

/** 
* \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;
}

希望这有帮助。如果您需要更多信息,请告诉我。

关于iOS 编程 : Problem extending UIButton class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6082094/

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