选中时在UIButton上添加/删除下划线

时间:2014-04-30 09:47:58

标签: ios objective-c uibutton

由于UISegmentedControl无法在IOS 7中自定义,并且由于我的项目需要一定程度的自定义,因此我决定手动创建两个UIButtons,使用bool变量来指示单击哪个按钮,然后重新加载tableView:< / p>

- (IBAction)pastFun:(id)sender {
    statusClicked = FALSE;
    NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"PAST"];

    [commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];

    [pastBut setAttributedTitle:commentString forState:UIControlStateNormal];
    [self.tableView reloadData];
}
- (IBAction)pendingFun:(id)sender {

    statusClicked = TRUE;
    [self.tableView reloadData];
}

在pastFun中,我添加了以下块,以便在选中时为该按钮加下划线,并且它可以正常工作:

NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"PAST"];

[commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];

[pastBut setAttributedTitle:commentString forState:UIControlStateNormal];

我想要做的是,当调用pendingFun(单击下一个按钮)时,从第一个按钮删除下划线然后在第二个按钮下划线,我似乎无法找到正确的方法来完成该操作。有什么想法怎么做?

1 个答案:

答案 0 :(得分:5)

我认为最好选择并取消选择按钮。

- (void)viewDidLoad
{
    [super viewDidLoad];        

    NSAttributedString *attrNormal = [[NSAttributedString alloc] initWithString:@"Button" attributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleNone]}];
    NSAttributedString *attrSelected = [[NSAttributedString alloc] initWithString:@"Button" attributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle]}];

    UIButton* boton = [[UIButton alloc] initWithFrame:CGRectMake(20, 50, 100, 30)];
    [boton setAttributedTitle:attrNormal forState:UIControlStateNormal];
    [boton setAttributedTitle:attrSelected forState:UIControlStateSelected];
    [boton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:boton];
}

- (void) buttonPressed:(UIButton *) boton {
    boton.selected = !boton.selected;
}

在您的情况下,使用两个按钮。您只需要保留一个属性来存储所选按钮(例如self.selectedButton)。在buttonPressed中执行此操作:

- (void) buttonPressed:(UIButton *) boton {
  self.selectedButton.selected = NO;
  self.selectedButton = boton;
  self.selectedButton.selected = YES;
}