iOS 滚动视图循环添加按钮
效果图
具体代码实现, 可直接copy代码, 可以简单封装一下,方便实用
#define Start_X 10.0f // 第一个按钮的X坐标
#define Start_Y 50.0f // 第一个按钮的Y坐标
#define Width_Space 5.0f // 2个按钮之间的横间距
#define Height_Space 20.0f // 竖间距
#define Button_Height 122.0f // 高
#define Button_Width 75.0f // 宽
@interface ViewController ()
{
NSArray*arr;
UIButton*_btn2;
}
@property (nonatomic, strong)UIScrollView *scrollView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
arr = @[@"无知",@"风云变幻",@"施耐庵",@"唉",@"西门吹雪",@"呵呵哒",@"快看看",@"窿窿啦啦",@"一杆禽兽狙",@"合欢花",@"暴走大事件",@"非诚勿扰",@"呵呵呵",@"无知",@"风云变幻",@"施耐庵",@"唉",@"西门吹雪",@"呵呵哒",@"快看看",@"窿窿啦啦",@"一杆禽兽狙",@"合欢花",@"暴走大事件",@"非诚勿扰",@"呵呵呵"];
NSIntegerx =0;
NSIntegery =5;
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, 30)];
self.scrollView.backgroundColor = [UIColor greenColor];
//设置显示内容的大小,这里表示可以下滑十倍原高度
//设置当滚动到边缘继续滚时是否像橡皮经一样弹回
self.scrollView.bounces = YES;
//设置滚动条指示器的类型,默认是白边界上的黑色滚动条
self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault;//还有UIScrollViewIndicatorStyleBlack、UIScrollViewIndicatorStyleWhite
//设置是否只允许横向或纵向(YES)滚动,默认允许双向
self.scrollView.directionalLockEnabled = YES;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.showsVerticalScrollIndicator =YES;
//设置是否采用分页的方式
// self.scrollView.pagingEnabled = YES;
//设置是否允许滚动
// self.scrollView.scrollEnabled = NO;
//设置是否可以缩放
// self.scrollView.maximumZoomScale = 2.0;//最多放大到两倍
// self.scrollView.minimumZoomScale = 0.5;//最多缩小到0.5倍
//设置是否允许缩放超出倍数限制,超出后弹回
// self.scrollView.bouncesZoom = YES;
//设置委托
// self.scrollView.delegate = self;
[self.view addSubview:self.scrollView];
for(NSIntegeri=0; i
NSString*str = [arrobjectAtIndex:i];
CGSize size = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]}];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(x, y, size.width,20);
btn.tag= i ;
[btnsetTitle:arr[i] forState:UIControlStateNormal];
[btnsetTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];\
btn.layer.masksToBounds = YES;
btn.layer.cornerRadius = 5;
btn.backgroundColor = [UIColor orangeColor];
[btnaddTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewaddSubview:btn];
x = x + size.width+10;//10为两个标签之间的宽度间隔
self.scrollView.contentSize = CGSizeMake(x, 30);
}
}
- (void)click:(UIButton*)button{
NSLog(@"%ld====%@",button.tag,arr[button.tag]);
if(_btn2== button) {
//上次点击过的按钮,不做处理
}else{
//本次点击的按钮设为红色
[buttonsetTitleColor:[UIColor redColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor grayColor];
//将上次点击过的按钮设为黑色
[_btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
_btn2.backgroundColor = [UIColor orangeColor];
}
_btn2= button;
}