1

我有一个名为“菜单”的类创建 UIButton:

.h 文件:

@interface Menu : NSObject

@property (strong) Forme *forme;
@property (strong) NSString *imageButtonName;
@property (strong) UIButton *button;

- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString*)imageButtonName button:(UIButton*)button;

@end

.m 文件:

#import "Menu.h"

@implementation Menu

@synthesize forme = _forme;
@synthesize button = _button;
@synthesize imageButtonName = _imageButtonName;

- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString *)imageButtonName button:(UIButton *)button
{
    if ((self = [super init]))
        {
            NSLog (@"test2");
            self.forme =[[Forme alloc]initWithClef:clef hauteur:hauteur largeur:largeur posY:posY posX:posX alpha:alpha];
            self.button = button;
            [button setFrame:CGRectMake(largeur, hauteur, posX, posY)];
            [button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
        }
    return self;
}

我想自动将创建的按钮显示到 ViewController 视图。有人可以帮助我吗?

4

3 回答 3

0

我认为您应该阅读一些手册和教程

只需在 init 方法中将此按钮添加到 viewcontroller 的视图中:

 [button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
 [self.view addSubview:button];
于 2013-03-21T09:57:14.903 回答
0

我认为只需在视图中添加一个按钮就可以了,调用:

[self.view addSubview:button]

初始化按钮后,您仍然需要使用 addSubview 将按钮“添加”到视图中,否则您的按钮将不会绘制在屏幕上。

于 2013-03-21T09:59:04.633 回答
0

并将 onView 参数添加到您的 initClef....

- (id) initWithClef:(int)clef hauteur:(int)hauteur largeur:(int)largeur posY:(int)posY posX:(int)posX alpha:(float)alpha imageButtonName:(NSString *)imageButtonName button:(UIButton *)button onView:(UIView *)view
{
    if ((self = [super init]))
    {
        NSLog (@"test2");
 //       self.forme =[[Forme alloc]initWithClef:clef hauteur:hauteur largeur:largeur posY:posY posX:posX alpha:alpha];
        self.button = button;
        [button setFrame:CGRectMake(largeur, hauteur, posX, posY)];
        [button setBackgroundImage:[UIImage imageNamed:imageButtonName] forState:UIControlStateNormal];
        [view addSubview:button];

    }
    return self;
}

在 viewController 中调用它

 Menu * menu2=[[Menu alloc] initWithClef:1 hauteur:30 largeur:30 posY:30 posX:30 alpha:1 imageButtonName:@"arti.png" button:b onView:self.view];
于 2013-03-21T23:35:45.963 回答