iOS 自定義九宮格

/**
     在此咱們使用的是Button來作
     由於不少時候須要文字也須要圖片顯示,因此Button比較合適
     */

- (void)CreatorBtn
{
    //列數
    NSInteger column = 4;
    //按鈕個數
    NSInteger buttonCount = 18;
    
    //按鈕的寬高
    CGFloat buttonW = self.view.frame.size.width / column;
    CGFloat buttonH = buttonW;
    
    for (int i = 0; i < buttonCount; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.frame = CGRectMake(((i % column) * buttonW), ((i / column) * buttonH), buttonW - 10, buttonH - 10);
        
        
        NSLog(@"%@",NSStringFromCGRect(btn.frame));
        
        [btn setBackgroundColor:[UIColor redColor]];
        
        //綁定tag,後邊監聽點擊
        btn.tag = i;
        
        [self.view addSubview:btn];
        
        
        //監聽按鈕點擊
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
}

- (void)btnAction:(UIButton *)btn
{
    //根據按鈕的tag來監聽點擊
    NSLog(@"點擊了第%ld個按鈕",(long)btn.tag);
    
}

 

相關文章
相關標籤/搜索