一 概述
本文介紹超級猜圖答案區和備選區按鈕思路
-
清除之前視圖中的子視圖
-
根據視圖的寬度和按鈕的個數,計算剩餘邊界的大小
-
根據答案長度和備選答案字符長度,設置按鈕的位置
-
將按鈕添加到答案區和備選區視圖
<!--more-->
二 效果圖
三 代碼
3.1 答案區
#define kButtonWidth 35 #define kButtonHeight 35 #define kButtonMargin 10 #define kTotalCol 7 //4.設置答案按鈕 //清除按鈕 for(UIView *view in self.optionsView.subviews) { [view removeFromSuperview]; } CGFloat answerW=self.answerView.bounds.size.width; NSUInteger length=question.answer.length; CGFloat answerX=(answerW-kButtonWidth*length-kButtonMargin*(length-1))*0.5; //創建所有答案的按鈕 for (int i=0; i<length; i++) { CGFloat x=answerX+i*(kButtonMargin+kButtonWidth); UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(x, 0, kButtonWidth, kButtonHeight)]; [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal]; [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer_heighted"] forState:UIControlStateHighlighted]; [self.answerView addSubview:btn]; }
3.2 備選區
//5.設置備選按鈕 CGFloat optionW=self.optionsView.bounds.size.width; CGFloat optionX=(optionW-kTotalCol*kButtonWidth-(kTotalCol-1)*kButtonMargin)*0.5; for (int i=0; i<question.options.count; i++) { int row=i/kTotalCol; int col=i%kTotalCol; CGFloat x=optionX+col*(kButtonMargin+kButtonWidth); CGFloat y=row*(kButtonMargin+kButtonHeight); UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(x, y, kButtonWidth,kButtonHeight)]; [btn setBackgroundImage:[UIImage imageNamed:@"btn_option"] forState:UIControlStateNormal]; [btn setBackgroundImage:[UIImage imageNamed:@"btn_option_heighted"] forState:UIControlStateHighlighted]; //設置備選區答案 [btn setTitle:question.options[i] forState:UIControlStateNormal]; [self.optionsView addSubview:btn]; [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];