gpt4 book ai didi

ios - 如何为 UIButton 创建 BOOL 属性以进行选中选择

转载 作者:行者123 更新时间:2023-11-29 10:42:44 24 4
gpt4 key购买 nike

我从数组中创建了许多带有循环的按钮,但我希​​望在单击任何按钮时,我可以使用一个名称为 Selected 的 bool 属性来检查选择状态此按钮。

当我点击它的任何按钮时,将背景更改为红色,当取消选择时,将背景更改为蓝色。

请指导我如何为任何按钮创建一个属性。

这是我的代码:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSMutableArray *arrayString = [[NSMutableArray alloc]initWithObjects:@"Mohammad",@"Hamidreza",@"Ahmad",@"Amirhossein",@"javad",@"asdasddasdsdasd", nil];

UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:20];
CGFloat x = 5;
CGFloat y = 80;
for (NSString *text in arrayString) {
UIButton *button = [[UIButton alloc]init];
CGFloat width = [self widthOfString:text withFont:myFont];
CGFloat height = [self heightOfString:text withFont:myFont];
if ((x + width) > 320) {
NSLog(@"after line");
x = 5;
y += (height+20)+10;
button.frame = CGRectMake(x, y, width+20, height+20);
[button setTitle:text forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
x += (width+20)+10;

}
else {
NSLog(@"this line");
button.frame = CGRectMake(x, y, width+20, height+20);
[button setTitle:text forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
x += (width+20)+10;
}
[button addTarget:self action:@selector(Selected:) forControlEvents:UIControlEventTouchUpInside];

}
}
-(IBAction)Selected:(id)sender{

if (//check sender button property bool selected) {

}
else {

}
}

最佳答案

试试这段代码:-

- (void)viewDidLoad
{
[super viewDidLoad];

[self.button setBackgroundImage:[self imageWithColor:[UIColor redColor]]forState:(UIControlStateHighlighted)];
[self.button setBackgroundImage:[self imageWithColor:[UIColor redColor]]forState:(UIControlStateSelected)];
[self.button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:(UIControlStateNormal)];
}

- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}

关于ios - 如何为 UIButton 创建 BOOL 属性以进行选中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720010/

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