1

我有 2 个在 .h 文件中创建的按钮和一个自定义视图

UIButton *btn_YourAccoun;
UIButton *btn_CreateAccoun;
UIView *view_top;

在 .m 文件中

- (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

请帮我

4

1 回答 1

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);

更新

您已在评论中询问此类错误的原因是什么。我假设您的意思是断言失败。断言是程序员为了确保不应该发生的事情没有发生而放入的东西。这可能是任何事情 - 如果您遇到断言失败,您需要更多地了解它发生在何时何地,才能知道出了什么问题。

在 Objective-C 中,每个对象都应该被分配一次并初始化一次。因为一个对象只应该被初始化一次,程序员已经断言它不应该被初始化更多。诸如buttonWithType:分配初始化对象之类的工厂方法,因此当您调用buttonWithType:然后initWithFrame:将其初始化两次时,断言失败了。

希望这是有道理的。

于 2013-09-23T07:46:46.090 回答