Change tab on custom UIView

时间:2017-06-16 20:36:26

标签: ios objective-c uiview

I basically just need to change tabs when the user taps a button on my custom UIView

This is my UIView implementation

public class newsalert
{
     //Other Properties         

     [JsonProperty(PropertyName = "category")]
     IList<Category> Categories {get;set;}
}

public class Category
{
     public string category {get;set;}
}

And my ViewController class:

@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;
}

This crashes because the UIView does not have a reference to the tabBarController. How do I call a method on my custom view's parent or what is the best approach to solve this?

2 个答案:

答案 0 :(得分:2)

据我所知,您可以在此处使用委托模式。因此,您创建一个名为CustomMenuViewDelegate的协议,并在此类型的CustomMenuView上声明一个弱属性。当调用menuItemTapped:方法时,您在CustomMenuViewDelegate属性上调用一个方法。您可以使ViewController符合委托协议,并将set设置为viewDidLoad方法中的委托。

答案 1 :(得分:0)

我最终决定使用这样的本地通知:

在我的自定义UIView

<?php echo $_POST['inputfieldvalue']; ?>  

UIViewController类

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