문제

I have a lot of places of a code that changes a view in UINavigationBar.
So the code is something like this:

UIButton *butt2=[UIButton buttonWithType:UIButtonTypeCustom ];

[butt2 setFrame:CGRectMake(285, 7, 30, 25)];
[butt2 setTag:2];
[butt2 setImage:[UIImage imageNamed:@"tag_icon.png"] forState:UIControlStateNormal];
[butt2 addTarget:self action:@selector(revealMenu:) forControlEvents:UIControlEventTouchDown];
[self.navigationController.navigationBar addSubview:butt2] ;

I want to create a method that gets argument of the different things in the code which is:
1. the image (easy)
2. The action of the button - AHA! This one I couldn't figure out how to do

도움이 되었습니까?

해결책

If you will decide to implement it as function it could be something like

void addNavigationButton(UIViewController *vc, UIImage *image, SEL action)
{
    UIButton *butt2=[UIButton buttonWithType:UIButtonTypeCustom ];

    [butt2 setFrame:CGRectMake(285, 7, 30, 25)];
    [butt2 setTag:2];
    [butt2 setImage:image forState:UIControlStateNormal];
    [butt2 addTarget:vc action:action forControlEvents:UIControlEventTouchDown];
    [vc.navigationController.navigationBar addSubview:butt2] ;
}

It should be called in your view controller

addNavigationButton(self, [UIImage imageNamed:@"tag_icon.png"], @selector(revealMenu:));

Another good idea - implement this function as a UIViewController's category method.

다른 팁

Add target prototype is:

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

If you use the same type "SEL" you should pass @selector(yourMethod) to your method.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top