您的位置:首页 > 产品设计 > UI/UE

【iOS】UI基础Day3-笔记(UIButton、购物车综合案例)

2017-04-16 19:48 477 查看

代码中使用UIButton

//实例化一个按钮
UIButton *button = [[UIButton alloc] init];
//设置按钮的frame
button.frame = CGRectMake(100, 100, 120, 30);
//设置按钮的背景颜色
button.backgroundColor = [UIColor greenColor];
//设置按钮普通状态下的文字和文字颜色
[button setTitle:@"普通状态" forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//设置按钮高亮状态下的文字和文字颜色
[button setTitle:@"高亮状态" forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
//将按钮添加到view
[self.view addSubview:button];
/* 监听按钮的点击
* Target: 目标 (让谁做事情)
* action: 方法 (做什么事情-->方法)
* Events: 事件
*/
[button addTarget:self action:@selector(demo) forControlEvents:UIControlEventTouchDragInside];
}

- (void)demo{
NSLog(@"%s",__func__);
}


综合案例(购物车添加&删除商品)

全局属性

//购物车View
@property (weak, nonatomic) IBOutlet UIView *shopCarView;
//添加按钮
@property (weak, nonatomic) IBOutlet UIButton *addButton;
//删除按钮
@property (weak, nonatomic) IBOutlet UIButton *removeButton;


添加按钮的点击事件

- 定义一些位置的常量和变量
//总列数
NSInteger allCols = 3;
//商品的长度和宽度
CGFloat width = 100;
CGFloat height = 100;
//水平间距和垂直间距
CGFloat hMargin = (self.shopCarView.frame.size.width - width * allCols) / (allCols - 1);
CGFloat vMargin = (self.shopCarView.frame.size.height - height * 2);
// 创建一个索引值
NSInteger index = self.shopCarView.subviews.count;
//设置X,Y值
CGFloat x = (hMargin + width) * (index % allCols);
CGFloat y = (vMargin + height) * (index / allCols);

- 创建商品添加到购物车
UIView *shop = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
//设置商品背景颜色
shop.backgroundColor = [UIColor redColor];
//添加到购物车
[self.shopCarView addSubview:shop];
//购物车数量不能大于6个
button.enabled = (index != 5);
//添加一个商品,就可以删除一个商品,此时要改变删除按钮的状态
self.removeButton.enabled = YES;


移除按钮的点击事件

//移除最后一个商品
UIView *lastShopView = [self.shopCarView.subviews lastObject];
[lastShopView removeFromSuperview];
//移除一个商品后,说明购物车有位置可以装商品,要改变添加按钮的状态
self.addButton.enabled = YES;
//如果购物车商品的数量为0,要设置删除按钮为不可点击
button.enabled = (self.shopCarView.subviews.count != 0);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: