我在复选框选项上创建了一个复选框,附加字符串,但是当我选择时 之后只有一个对象,我的对象包含一个逗号,如果是用户,我不想要逗号 只选中复选框。如果用户选择全部三个,则逗号分隔值很好,但当用户随机选择时,我们遇到问题。以下是我的代码
- (IBAction)buttonAction:(UIButton *)sender {
if (sender.tag == 0) {
if (isPaint) {
isPaint = NO;
[self.filterDict setValue:@"" forKey:@"one"];
} else {
isPaint = YES;
[self.filterDict setValue:@"1" forKey:@"one"];
}
}
if (sender.tag == 1) {
if (isDecor) {
isDecor = NO;
[self.filterDict setValue:@"" forKey:@"two"];
} else {
isDecor = YES;
[self.filterDict setValue:@"2" forKey:@"two"];
}
}
if (sender.tag == 2) {
if (isCommunity) {
isCommunity = NO;
[self.filterDict setValue:@"" forKey:@"three"];
} else {
isCommunity = YES;
[self.filterDict setValue:@"3" forKey:@"three"];
}
}
}
- (IBAction)doneFilter:(UIButton *)sender {
NSMutableString *filterType = [[NSMutableString alloc] init];
if ([self.filterDict objectForKey:@"one"] != nil) {
paintStr = [NSString stringWithFormat:@"%@,", [self.filterDict objectForKey:@"one"]];
} if ([self.filterDict objectForKey:@"two"] != nil) {
decorStr = [NSString stringWithFormat:@"%@,", [self.filterDict objectForKey:@"two"]];
} if ([self.filterDict objectForKey:@"three"] != nil) {
communityStr = [NSString stringWithFormat:@"%@", [self.filterDict objectForKey:@"three"]];
}
if (paintStr != nil) {
[filterType appendString:paintStr];
} if (decorStr != nil) {
[filterType appendString:decorStr];
} if (communityStr != nil) {
[filterType appendString:communityStr];
}
}
提前致谢。
答案 0 :(得分:0)
如果存在现有值,则只附加逗号:
- (IBAction)doneFilter:(UIButton *)sender {
NSMutableString *filterType = [[NSMutableString alloc] init];
paintStr = self.filterDict[@"one"];
decorStr = self.filterDict[@"two"];
communityStr = self.filterDict[@"three"];
if (paintStr) {
if (filterType.length) {
[filterType appendString:@","];
}
[filterType appendString:paintStr];
}
if (decorStr) {
if (filterType.length) {
[filterType appendString:@","];
}
[filterType appendString:decorStr];
}
if (communityStr) {
if (filterType.length) {
[filterType appendString:@","];
}
[filterType appendString:communityStr];
}
}
请注意如何使用现代Objective-C语法清理和更新此代码。