我有两个在.h文件中创建的按钮和一个自定义视图
UIButton *btn_YourAccoun;
UIButton *btn_CreateAccoun;
UIView *view_top;
<。>文件中的
- (void)viewDidLoad
{
[super viewDidLoad];
view_top=[[UIView alloc]initWithFrame:CGRectMake(0, 0,320,60)];
[view_top setBackgroundColor:[UIColor colorWithRed:80.0/255.0 green:79.0/255.0 blue:81.0/255.0 alpha:1.0]];
[self.view addSubview:view_top];
UILabel *labelheader=[[UILabel alloc]initWithFrame:CGRectMake(140, 5, 140, 20)];
[labelheader setText:@"CREATE AN ACCOUNT"];
[labelheader setTextColor:[UIColor whiteColor]];
[labelheader setTextAlignment:UITextAlignmentLeft];
[view_top addSubview: labelheader];
btn_YourAccoun=[[UIButton buttonWithType:UIButtonTypeCustom]init ];
[btn_YourAccoun setFrame:CGRectMake(0,0,65,44)];
[btn_YourAccoun setTitle:@"YOUR ACCOUNT" forState:UIControlStateNormal];
[btn_YourAccoun setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn_YourAccoun.titleLabel setFont:[UIFont systemFontOfSize:12.0]];
[btn_YourAccoun setBackgroundColor:[UIColor clearColor]];
CALayer *layer1=[btn_YourAccoun layer];
layer1.backgroundColor=[UIColor colorWithRed:232.0/255 green:230.0/255.0 blue:236.0/255.0 alpha:1.0].CGColor;
layer1.borderWidth=2.0;
layer1.borderColor=[UIColor colorWithRed:184.0/255 green:185.0/255.0 blue:188.0/255.0 alpha:1.0].CGColor;
[view_top addSubview:btn_YourAccoun];
btn_CreateAccoun=[[UIButton buttonWithType:UIButtonTypeCustom]initWithFrame:CGRectMake(270, 0, 55,44)];
[btn_CreateAccoun setTitle:@"Create" forState:UIControlStateNormal];
[btn_CreateAccoun setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn_CreateAccoun.titleLabel setFont:[UIFont systemFontOfSize:12.0]];
[btn_CreateAccoun setBackgroundColor:[UIColor clearColor]];
CALayer *layer2=[btn_CreateAccoun layer];
layer2.backgroundColor=[UIColor colorWithRed:232.0/255 green:230.0/255.0 blue:236.0/255.0 alpha:1.0].CGColor;
layer2.borderWidth=2.0;
layer2.borderColor=[UIColor colorWithRed:184.0/255 green:185.0/255.0 blue:188.0/255.0 alpha:1.0].CGColor;
[view_top addSubview:btn_CreateAccoun];
}
当我为btn_YourAccoun
设置框架时,它会出错错误 - :断言失败 - [UIButton initWithFrame:], /SourceCache/UIKit_Sim/UIKit-1912.3/UIButton.m:921
请帮帮我
答案 0 :(得分:4)
你有这个:
btn_CreateAccoun = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(270, 0, 55,44)];
您不应该使用工厂方法和初始化程序。你要么:
btn_CreateAccoun = [[UIButton alloc] initWithFrame:CGRectMake(270, 0, 55,44)];
或:
btn_CreateAccoun = [UIButton buttonWithType:UIButtonTypeCustom];
btn_CreateAccoun.frame = CGRectMake(270, 0, 55,44);
更新
您在评论中询问了此类错误的原因。我认为你的意思是断言失败。 assertion是程序员所做的事情,以确保不会发生的事情没有发生。这可能是任何事情 - 如果你遇到断言失败,你需要更多地了解它发生的时间和地点,以便知道出了什么问题。
在Objective-C中,每个对象应分配一次并初始化一次。因为一个对象只应初始化一次,所以程序员已经断言它不应该初始化多于那个。工厂方法(例如buttonWithType:
)分配和初始化对象,因此当您调用buttonWithType:
然后initWithFrame:
时,您已将其初始化两次,因此断言失败。
希望这是有道理的。