iOS for迴圈建立button,button的寬度依據上面的文字來自適應.

來源:互聯網
上載者:User

標籤:contex   ati   dict   csdn   cto   設定   文字   length   cti   

近期須要使用一個標籤頁,尋思自己寫一個demo.
標籤的大小依據上面的文字來自適應大小,須要依據後台返回的資料自己主動換行.沒有加入
NSArray *arr = @[@"無知",@"風雲變幻",@"施耐庵",@"唉",@"西門吹雪",@"呵呵噠",@"快看看",@"窿窿啦啦",@"一杆禽獸狙",@"合歡花",@"暴走大事件",@"非誠勿擾",@"呵呵呵"];    CGFloat w = 0;//儲存前一個button的寬以及前一個button距離螢幕邊緣的距離    CGFloat h = 200;//用來控制button距離父視圖的高    for (int i = 0; i < arr.count; i++) {        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];        button.tag = 100 + i;        button.backgroundColor = [UIColor greenColor];        [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];        //依據計算文字的大小                NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};        CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;        //為button賦值        [button setTitle:arr[i] forState:UIControlStateNormal];        //設定button的frame        button.frame = CGRectMake(10 + w, h, length + 15 , 30);        //當button的位置超出螢幕邊緣時換行 320 僅僅是button所在父視圖的寬度        if(10 + w + length + 15 > 320){            w = 0; //換行時將w置為0            h = h + button.frame.size.height + 10;//距離父視圖也變化            button.frame = CGRectMake(10 + w, h, length + 15, 30);//重設button的frame        }        w = button.frame.size.width + button.frame.origin.x;        [self.view addSubview:button];    }點擊事件- (void)handleClick:(UIButton *)btn{    NSLog(@"%ld",btn.tag);}







iOS for迴圈建立button,button的寬度依據上面的文字來自適應.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.