gpt4 book ai didi

ios - 为动态创建的 UIButtons 选择/取消选择

转载 作者:行者123 更新时间:2023-11-28 18:55:10 27 4
gpt4 key购买 nike

我将解释场景:我在 for 循环中动态创建三个 UIButton。条件是默认情况下第一个按钮应该有边框。现在如果我们选择其他按钮,前一个按钮的边框应该消失,现在应该为所选按钮显示边框。

for (int btnsCount = 0 ; btnsCount <[DataList count]; btnsCount++) {
self.graphSubDataButton = [[UIButton alloc] init];


self.graphSubDataButton.frame = CGRectMake(buttonsOffset, 0, 120, 40);
[self.graphSubDataButton setTitleColor:UIColorFromRGB(0x548DCD) forState:UIControlStateNormal];

[self.graphSubDataButton.titleLabel setFont:[UIFont fontWithName:AVENIR_NEXT_MEDIUM size:13.0f]];

self.graphSubDataButton.tag = btnsCount+1;
[self.graphSubDataButton addTarget:self action:@selector(enableRespectiveButton2:) forControlEvents:UIControlEventTouchUpInside];
buttonsOffset = buttonsOffset+30 + self.graphSubDataButton.frame.size.width ;

if (self.graphSubDataButton.tag==1)
{

[self.graphSubDataButton.layer setBorderWidth:1.2f];
[self.graphSubDataButton.layer setBorderColor:[UIColorFromRGB(0x3070BA) CGColor]];
[self.graphSubDataButton.layer setCornerRadius:8.0f];
}
}


-(void) enableRespectiveButton2:(UIButton *) sender
{
}

最佳答案

我对你的代码结构做了一些改动以使其正常工作,如果你有不明白的地方可以评论。

NSInteger defaultSelectedTag = 1;
for (int btnsCount = 0 ; btnsCount <[DataList count]; btnsCount++) {
UIButton *graphSubDataButton = [UIButton buttonWithType:UIButtonTypeCustom];
graphSubDataButton.frame = CGRectMake(buttonsOffset, 0, 120, 40);
[graphSubDataButton setTitleColor:UIColorFromRGB(0x548DCD) forState:UIControlStateNormal];
[graphSubDataButton.titleLabel setFont:[UIFont fontWithName:AVENIR_NEXT_MEDIUM size:13.0f]];
graphSubDataButton.tag = btnsCount+1;
[graphSubDataButton addTarget:self action:@selector(enableRespectiveButton:) forControlEvents:UIControlEventTouchUpInside];
buttonsOffset = buttonsOffset+30 + self.graphSubDataButton.frame.size.width ;
//add your button somewhere
//e.g.
//[self.view addSubview:graphSubDataButton];
if (graphSubDataButton.tag == defaultSelectedTag) {
[self setBorderForButton:graphSubDataButton];
}
}

- (void) setBorderForButton:(UIButton *)sender {
[sender.layer setBorderWidth:1.2f];
[sender.layer setBorderColor:[UIColorFromRGB(0x3070BA) CGColor]];
[sender.layer setCornerRadius:8.0f];
}

- (void) enableRespectiveButton2:(UIButton *) sender {
for(UIButton *buttons in [sender.superview subviews]) {
if([buttons isKindOfClass:[UIButton class]]) {
if(![buttons isEqual:sender]) {
//add logic to, remove borders
//buttons.layer.borderWidth = 0.0f;
}
}
}
[self setBorderForButton:sender];
}

关于ios - 为动态创建的 UIButtons 选择/取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34742534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com