美好的一天。我尝试将事件添加到细分受众群控制中,但这总是让我大吃一惊。我在课堂上创建了一个属性

#import <UIKit/UIKit.h>

@interface Events : UINavigationController{
    UISegmentedControl *segmentedControl;
}
@property (nonatomic, retain) UISegmentedControl *segmentedControl;
-(void)changeSegment:(id)sender;
@end


然后在.m文件中添加一个子视图

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
         self.segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                                [NSArray arrayWithObjects:
                                                 [NSString stringWithString:NSLocalizedString(@"Трансляции", @"")],
                                                 [NSString stringWithString:NSLocalizedString(@"Мафия", @"")],

                                                 nil]];
        segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
        [segmentedControl setSelectedSegmentIndex:0];



        //[segmentedControl setFrame:[self.navigationBar bounds]];
        CGRect rect = [self.navigationBar bounds];
        rect.size.width = rect.size.width - 40;
        rect.size.height = rect.size.height - 15;
        rect.origin.y =  rect.origin.y + 7;
        rect.origin.x =  rect.origin.x + 17;
        [segmentedControl setFrame:rect];

        [self.navigationBar addSubview:segmentedControl];

    }
    return self;
}


然后在ViewDidLoad中,我尝试添加事件

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.segmentedControl addTarget:self action:@selector(changeSegment:)
               forControlEvents:UIControlEventValueChanged];

}


以及事件的描述

-(void)changeSegment{
    if(segmentedControl.selectedSegmentIndex == 0){

    }
    if(segmentedControl.selectedSegmentIndex == 1){

    }
}


但它永远不会进入此功能。并给我错误[Events changeSegment:]:无法识别的选择器发送到实例0x6833bf0

最佳答案

您声明了-(void)changeSegment:(id)sender并将选择器@selector(changeSegment:)添加到段控件中,但是,实现了-(void)changeSegment@selector(changeSegment),请注意缺少的:。

只需更改此:

-(void)changeSegment{
    if(segmentedControl.selectedSegmentIndex == 0){

    }
    if(segmentedControl.selectedSegmentIndex == 1){

    }
}


对此:

-(void)changeSegment:(id)sender{
    if(segmentedControl.selectedSegmentIndex == 0){

    }
    if(segmentedControl.selectedSegmentIndex == 1){

    }
}

10-06 01:31