UIButton没有被实例化

时间:2014-07-18 08:51:17

标签: ios objective-c xcode uiviewcontroller uibutton

我试图从已经在Interface Builder中创建的UIView中创建一个简单的UIButton,但没有任何事情发生。 我已将以下代码附加到视图中:

" DetailViewTwo.h":

#import <UIKit/UIKit.h>

@interface DetailViewTwo : UIView

@property (nonatomic) bool viewIsShown;
@property (nonatomic) float lastY;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) NSMutableArray *radioArray;


-(void)createOption:(NSString *)legenda Value:(NSString *)value action:(SEL)action;
-(void)clearView:(NSString *)novoNome;
-(void)escolherRota:(id)sender;
@end

&#34; DetailViewTwo.m&#34;:

#import "DetailViewTwo.h"
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation DetailViewTwo

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _viewIsShown=false;
        [self.layer setMasksToBounds:YES];
        self.layer.cornerRadius=6;

        UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        but.frame= CGRectMake(100, 15, 15, 15);
        [but setTitle:@"Ok" forState:UIControlStateNormal];
        [but addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:but];
    }
    return self;
}
@end

(哦,我的&#39; self.layer.cornerRadius = 6;&#39;也不起作用,是否相关?)

3 个答案:

答案 0 :(得分:4)

如果您在故事板中创建了此视图,则应使用 -initWithCoder:初始化代替-initWithFrame:。 此外,您应该将按钮添加到self.view而不是superview。

- (id)initWithCoder:(NSCoder *)aDecoder {

    if(self = [super initWithCoder:aDecoder]) {
        //Your code goes here
    }
}

答案 1 :(得分:0)

您需要将UIButton添加到View

[self.superview addSubview:but];

应该是

[self addSubview:but];

答案 2 :(得分:0)

我有一个在视图中实例化(添加)按钮的解决方案。根据您的代码,您只需将此[self.superview addSubview:but];替换为[self.view addSubview:but];即可。

 UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                but.frame= CGRectMake(100, 15, 15, 15);
                [but setTitle:@"Ok" forState:UIControlStateNormal];
                [but addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:but]; // Changes done