1.创建按钮方法封装
#pragma mark 添加按钮
- (void)addButtonWithImage:(NSString *)image
highImage:(NSString *)highImage
disableImage:(NSString *)disableImage
frame:(CGRect)frame
action:(SEL)action{
// 创建按钮
UIButton *btn = [[UIButton alloc] init];
// 设置背景图片
[btn setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:highImage] forState:UIControlStateHighlighted];
[btn setBackgroundImage:[UIImage imageNamed:disableImage] forState:UIControlStateDisabled];
// 设置位置和尺寸
btn.frame = frame;
// 监听按钮点击
[btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
// 添加按钮
[self.view addSubview:btn];
}
调用
[self addButtonWithImage:@"add"
highImage:@"add_highlighted"
disableImage:@"add_disabled"
frame:CGRectMake(30, 30, 50, 50)
action:@selector(add)];
2.在一个购物车视图添加商品
@property (weak, nonatomic) IBOutlet UIView *shopsView;
- (void)add{
// 这行代码把范围圈定在 shopsView ( : UIView) 中
self.shopsView.clipsToBounds = YES;
// 每一个商品的尺寸
CGFloat shopW = 50;
CGFloat shopH = 70;
// 一行的列数
int cols = 4;
// 每一列之间的间距
CGFloat colMargin = (self.shopsView.frame.size.width - cols * shopW) / (cols - 1);
// 每一行之间的间距
CGFloat rowMargin = 10;
// 创建一个父控件(整体:存放图片和文字)
UIView *shopView = [[UIView alloc] init];
shopView.backgroundColor = [UIColor redColor];
// 商品的索引
NSUInteger index = self.shopsView.subviews.count;
// 商品的x值
NSUInteger col = index % cols;
CGFloat shopX = col * (shopW + colMargin);
// 商品的y值
NSUInteger row = index / cols;
CGFloat shopY = row * (shopH + rowMargin);
shopView.frame = CGRectMake(shopX, shopY, shopW, shopH);
[self.shopsView addSubview:shopView];
// 添加图片
UIImageView *iconView = [[UIImageView alloc] init];
iconView.image = [UIImage imageNamed:@"danjianbao"];
iconView.frame = CGRectMake(0, 0, shopW, shopW);
iconView.backgroundColor = [UIColor blueColor];
[shopView addSubview:iconView];
// 添加文字
UILabel *label = [[UILabel alloc] init];
label.text = @"单肩包";
label.frame = CGRectMake(0, shopW, shopW, shopH - shopW);
label.font = [UIFont systemFontOfSize:11];
label.textAlignment = NSTextAlignmentCenter;
[shopView addSubview:label];
}
网友评论