Monday 15 August 2011

objective c - UIButton and UIViewContoller IOS7 -



objective c - UIButton and UIViewContoller IOS7 -

i'm new objc , i'm trying create button outside viewcontroller file (following mvc paradigm). did:

.h

@interface mainmenu : uibutton -(uibutton *)addbutton; @end

.m

@implementation mainmenu -(uibutton *)addbutton { uibutton* button = [[uibutton alloc] initwithframe:cgrectmake(50.0, 50.0, 200.0, 75.0)]; [button setbackgroundcolor:[uicolor colorwithred:1.0 green:1.0 blue:0.0 alpha:1.0]]; [button settitle:@"title" forstate:uicontrolstatenormal]; homecoming button; } @end

in viewcontroller want create button on screen , create respond touch event. so

.m @implementation viewcontroller -(void)viewdidload { [super viewdidload]; mainmenu *menubutton = [[mainmenu alloc] init]; [menubutton addtarget:self action:@selector(buttonclick) forcontrolevents:uicontroleventtouchupinside]; [self.view addsubview:menubutton]; } -(void)buttonclick { nslog(@"you clicked on button!!!"); } @end

i can create work implementing in viewcontroller.m file, wish have separated. code above doesnt show me button

second thing: tried add together addtarget:action:forcontrolevents: method mainmenu.m instead of viewcontroller.m , couldnt create work because need pass viewcontroller target , method buttonclick viewcontroller.m selector (i guess)

so i'm interesting how create right according mvc? thanks!

they way doing bit wrong, subclassing uibutton , have instance method addbutton returns button, don't create sense. either can add together class level method or subclass , add together init method fulfill requirements.

better if want create custom button , want add together target action this

@interface custombutton : uibutton - (instancetype)initwithtarget:(id)target andaction:(sel)action; @end in .m file @implementation custombutton - (instancetype)initwithtarget:(id)target andaction:(sel)action { self = [super initwithframe::cgrectmake(50.0, 50.0, 200.0, 75.0)]; if (self) { [self setbackgroundcolor:[uicolor colorwithred:1.0 green:1.0 blue:0.0 alpha:1.0]]; [self settitle:@"title" forstate:uicontrolstatenormal]; [self addtarget:target action:action forcontrolevents:uicontroleventtouchupinside]; } homecoming self; } @end

and can utilize anywhere

[self.view addsubview:[custombutton alloc] initwithtarget:self andaction:@selector(name)]];

objective-c ios7 model-view-controller

No comments:

Post a Comment