iOS开发--设置button选中状态

    //设置一个View

     _buttonView = [[ UIView alloc ] initWithFrame : CGRectMake ( 0 , STATUS_BAR + NAVIGATION_HIGHT , WINSIZE . width , NAVIGATION_HIGHT )];

    _buttonView.backgroundColor = [UIColor yellowColor];

    [self.view addSubview:_buttonView];

    

    //创建四个按钮

    NSArray * messageArray = @[@"最新消息",@"我关注的",@"我发布的",@"查询"];

#define WIDTH WINSIZE.width/messageArray.count

    

    for (NSUInteger i= 0; i< messageArray.count; i++) {

        NSString * name = [NSString stringWithFormat:@"%@",messageArray[i]];

        RHRemoveHighlightOfTheButton * item = [RHViewFactory generalButtonInitWithFrame:CGRectMake(i*WIDTH, 0, WIDTH, NAVIGATION_HIGHT) name:name imageName:nil];

        

        //添加事件

        [item addTarget:self action:@selector(messageItemOnClick:) forControlEvents:UIControlEventTouchUpInside];

        //设置tag

        item.tag = BUTTON_ITEM_TAG + i;

        

//将创建的button添加到view上面

        [_buttonView addSubview:item];

        

//默认选中第一个

        if (item.tag == BUTTON_ITEM_TAG) {

            item.selected = YES;

        }

    }

#undef WIDTH

}

//button事件


- (void)messageItemOnClick:(RHGeneralButton *)item

{

    for (RHGeneralButton * button in _buttonView.subviews) {

        if (button.tag != item.tag) {

            button.selected = NO;

        } else

            button.selected = YES;

    }

}

你可能感兴趣的:(iOS开发,ios开发,UIButton,选中)