button 动态修改背景颜色无效,该如何动态修改背景颜色???
来源:3-4 栏目分组模块标题按钮的边框
axiba
2018-11-29 10:08:00

2回答
你可以说明一下你现在的运行结果是什么样的嘛?然后在描述一下你想动态改变颜色的结果是什么样的?描述好需求,便于老师更精确地帮助你解决问题。助学习愉快~
axiba
提问者
2018-11-29
```Objective-c
// common.h文件
#define UISCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define UISCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define PINKCOLOR [UIColor colorWithRed:216.0/255.0 green:114.0/255.0 blue:213.0/255.0 alpha:1.0]
```
```Objective-c
#import "MiddleView.h"
#import "common.h"
@interface MiddleView() {
NSArray *types;
UIScrollView *scrollView;
}
@end
@implementation MiddleView
- (instancetype)initWithFrame:(CGRect)frame newsType:(NSArray *)type
{
self = [super initWithFrame:frame];
if (self) {
types = type;
[self addScrollView];
}
return self;
}
-(void) addScrollView {
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
scrollView.contentSize = CGSizeMake(100*types.count, 40);
scrollView.contentOffset = CGPointMake(0, 0);
scrollView.backgroundColor = PINKCOLOR;
scrollView.showsHorizontalScrollIndicator = false;
scrollView.bounces = NO;
[self addSubview:scrollView];
for (int i = 0; i< types.count; i++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i*100, 0, 100, 40)];
NSString *buttonTitle = [types objectAtIndex:i];
[button setTitle:buttonTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:12.0];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
button.tag = 10000+i;
[scrollView addSubview:button];
if (i == 0) {
button.backgroundColor = [UIColor grayColor];
}
}
}
-(void)buttonAction:(UIButton *)button {
button.backgroundColor = [UIColor grayColor];
for (UIButton *item in scrollView.subviews) {
if (item.tag >= 10000 && item.tag <= 10000+types.count &&(item.tag !=button.tag)){
NSLog(@"%ld", (long)item.tag);
button.backgroundColor = [UIColor redColor];
}
}
}
@end
```
这个段代码的意思,首先给选中的button设置grayColor,然后循环scrollView里的button,判断如果不是当前点击的button,把其它的button都变成button.backgroundColor = [UIColor redColor];
```Objective-c
-(void)buttonAction:(UIButton *)button {
button.backgroundColor = [UIColor grayColor];
for (UIButton *item in scrollView.subviews) {
if (item.tag >= 10000 && item.tag <= 10000+types.count &&(item.tag !=button.tag)){
NSLog(@"%ld", (long)item.tag);
button.backgroundColor = [UIColor redColor];
}
}
}
```
但是运行效果是当前点击的button变成了button.backgroundColor = [UIColor redColor];,其它的button没变化
相似问题