標籤:索引 enable 建立 enabled 顏色 back style 練習 inter
Assets.xcassets圖片是拖到右邊裡面去的。
//// ViewController.m// 03-綜合練習//#import "ViewController.h"@interface ViewController ()// 購物車@property (weak, nonatomic) IBOutlet UIView *shopCarView;// 添加按鈕@property (weak, nonatomic) IBOutlet UIButton *addButton;// 刪除按鈕@property (weak, nonatomic) IBOutlet UIButton *removeButton;// 全域的下標//@property (nonatomic, assign) NSInteger index;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // 給下標賦值// self.index = 0; // // 裁剪多餘部分(不可取)// self.shopCarView.clipsToBounds = YES;}/** * 添加到購物車 * * @param button 按鈕 */- (IBAction)add:(UIButton *)button {/***********************1.定義一些常量*****************************/ // 1.總列數 NSInteger allCols = 3; // 2.商品的寬度 和 高度 CGFloat width = 80; CGFloat height = 100; // 3.求出水平間距 和 垂直間距 CGFloat hMargin = (self.shopCarView.frame.size.width - allCols * width) / (allCols -1); CGFloat vMargin = (self.shopCarView.frame.size.height - 2 * height) / 1; // 4. 設定索引 NSInteger index = self.shopCarView.subviews.count; // 5.求出x值 CGFloat x = (hMargin + width) * (index % allCols); CGFloat y = (vMargin + height) * (index / allCols); /***********************2.建立一個商品*****************************/ // 1.建立商品的view UIView *shopView = [[UIView alloc] init]; // 2.設定frame shopView.frame = CGRectMake(x, y, width, height); // 3.設定背景顏色 shopView.backgroundColor = [UIColor greenColor]; // 4.添加到購物車 [self.shopCarView addSubview:shopView]; /***********************3.設定按鈕的狀態*****************************/// if (index == 5) {// button.enabled = NO;// } button.enabled = (index != 5); // 5.設定刪除按鈕的狀態 self.removeButton.enabled = YES; // 讓下標+1// self.index += 1;}/** * 從購物車中刪除 * * @param button 按鈕 */- (IBAction)remove:(UIButton *)button { // 1. 刪除最後一個商品 UIView *lastShopView = [self.shopCarView.subviews lastObject]; [lastShopView removeFromSuperview]; // 2.設定索引值 -1// self.index -= 1; // 3. 設定添加按鈕的狀態 self.addButton.enabled = YES; // 4. 設定刪除按鈕的狀態 /* if (self.shopCarView.subviews.count == 0) { self.removeButton.enabled = NO; } */ self.removeButton.enabled = (self.shopCarView.subviews.count != 0); }@end
ios12--簡易購物車