Can you hard code IBActions and IBOutlets, rather than drag them manually in Interface Builder?

一世执手 提交于 2019-11-26 20:43:42

问题


Is it possible to to hard code the IBActions and IBOutlets in code, instead of drag-connecting them in Interface Builder?


回答1:


Yes it is poosible...

sample code

UIButton *btnDetail = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;

        [btnDetail setFrame:CGRectMake(250.0f, 15.0f, 65.0f, 20.0f)] ;
        //btnDetail.backgroundColor = [UIColor grayColor];
        [btnDetail setTitle:@"Detail" forState:UIControlStateNormal];
        [btnDetail setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
        [btnDetail.titleLabel setFont:[UIFont fontWithName:@"Verdana" size:12]];
        [btnDetail setBackgroundColor:[UIColor clearColor]];
        [btnDetail sizeThatFits:btnDetail.frame.size];
        [self.view addSubview:btnDetail];
//IBAction
        [btnDetail addTarget:self 
                   action:@selector(ShowSavingAccountDetail:)
         forControlEvents:UIControlEventTouchUpInside];

        [btnDetail setImage:[UIImage imageNamed:@"btn-detail.png"] forState:UIControlStateNormal];



回答2:


The concept and sole purpose of IBAction and IBOutlet is to provide Interface Builder with means to connect the xib with your code.

If you don't want to use Interface Builder with your code, you don't need IBAction or IBOutlet, you need them ONLY to use objects (buttons, textfields, etc.) that were instanciated in your xib from your classes.

With that said, mihirpmehta's answer is the correct way to programmatically add UI elements to your view and add actions to them.



来源:https://stackoverflow.com/questions/2544279/can-you-hard-code-ibactions-and-iboutlets-rather-than-drag-them-manually-in-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!