2017-06-16 163 views
0

我基本上只需要當用戶點擊我的自定義UIView的一個按鈕來更改選項卡更改標籤

這是我的UIView實現

@implementation CustomMenuView 
- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 

     UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 135.0, 40.0)]; 
     searchButton.backgroundColor = [UIColor clearColor]; 
     [searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
     searchButton.titleLabel.font = [UIFont systemFontOfSize:15]; 
     [searchButton setTitle:@"Search" forState:UIControlStateNormal]; 
     searchButton.tag = 0; 
     [searchButton addTarget:self action:@selector(menuItemTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     [self addSubview:searchButton]; 


    } 
    return self; 
} 

-(void)menuItemTapped:(UIButton*)sender{ 
    self.tabBarController.selectedIndex = sender.tag; 
} 

而且我的ViewController類:

UIView *menuView; 

    - (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    CGFloat height = [UIScreen mainScreen].bounds.size.height; 
    menuView = [[CustomMenuView alloc]initWithFrame:CGRectMake(0, 60, 135, height)]; 
    [self.view addSubview:menuView]; 
} 

由於UIView沒有對tabBarController的引用,因此崩潰。如何在我的自定義視圖的父級上調用方法或者解決此問題的最佳方法是什麼?

回答

0

我最終決定使用本地通知如下:

在我的自定義的UIView

-(void)menuItemTapped:(UIButton*)sender{ 
     NSDictionary* userInfo = @{@"tab": @(sender.tag)}; 
     NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; 
     [nc postNotificationName:@"MenuItemSelected" object:self userInfo:userInfo]; 

UIViewController類

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

     [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(receiveMenuItemSelectedNotification:) 
                name:@"MenuItemSelected" 
                object:nil]; 
    } 

    -(void) receiveMenuItemSelectedNotification:(NSNotification*)notification 
    { 
     if ([notification.name isEqualToString:@"MenuItemSelected"]) 
     { 
      NSDictionary* userInfo = notification.userInfo; 
      NSNumber* tab = (NSNumber*)userInfo[@"tab"]; 
      NSLog (@"Successfully received test notification! %i", tab.intValue); 
      self.tabBarController.selectedIndex = tab.intValue; 

     } 
    } 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MenuItemSelected" object:nil]; 

} 
2

據我所知,你在這裏可以使用委託模式。因此,您創建一個名爲CustomMenuViewDelegate的協議,並在此類型的CustomMenuView上聲明一個弱屬性。當調用menuItemTapped:方法時,您調用CustomMenuViewDelegate屬性的方法。您可以使您的ViewController符合委託協議,並將其設置爲viewDidLoad方法中的委託。

+0

感謝我upvoted和敢打賭,這工作得很好,但我還是決定爲此使用本地通知。 –

+0

當然,很高興你找到了解決方案。請記住,使用NSNotification這些東西往往會被認爲是反模式有些(見[這個偉大的職位(https://davidnix.io/post/stop-using-nsnotificationcenter/))。不過,我猜想真正重要的是它完成了工作:) –