一、介紹
本人做的app涉及的是教育行業,所以關于練習題的開發肯定是家常便飯。例如,選擇題、填空題、連線題、判斷題等,每一種題型都需要技術去實現,沒啥多大難度,這里呢,就給出實現連線題的核心代碼吧。過了年后,好久沒寫筆記了,今天就簡單開始吧~~~
?
二、思想
采用上下文在畫圖的方法,首先確定起點和終點的坐標,然后通過兩點畫一條直線。
?
三、代碼
(1)常量定義
lianXianHeader.h


// // LianXianHeader.h // LianxianDemo // // Created by 夏遠全 on 2018/2/9. // Copyright ? 2018年 beijing. All rights reserved. // #ifndef LianXianHeader_h #define LianXianHeader_hstatic CGFloat const BWidth = 60; //按鈕的寬度 static CGFloat const BHeight = 40; //按鈕的高度 static CGFloat const margin = 40; //按鈕與屏幕的左邊距、右邊距 static CGFloat const Lpadding = 20; //左邊按鈕上下間距 static CGFloat const Rpadding = 40; //右邊按鈕上下間距static NSString* const kBeginPositionNotification = @"kBeginPositionNotification"; static NSString* const kEndPositionNotification = @"kEndPositionNotification"; static NSString* const kClearAllLineNotification = @"kClearAllLineNotification"; static NSString* const kFreshDrawLineNotification = @"kFreshDrawLineNotification";#endif /* LianXianHeader_h */
?
(2)連線模型
lianXianModel.h


// // LianXianModel.h // LianxianDemo // // Created by 夏遠全 on 2018/2/8. // Copyright ? 2018年 beijing. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h>@interface LianXianModel : NSObject @property (nonatomic, strong) NSArray *questions; @property (nonatomic, strong) NSArray *options; @property (nonatomic, strong) NSArray *relationships; @end
lianXianModel.m


// // LianXianModel.m // LianxianDemo // // Created by 夏遠全 on 2018/2/8. // Copyright ? 2018年 beijing. All rights reserved. // #import "LianXianModel.h"@implementation LianXianModel@end
?
(3)繪制連線
lianXianDrawView.h


// // LianxianDrawView.h // Ubbsz // // Created by 夏遠全 on 2018/2/9. // Copyright ? 2018年 beijing. All rights reserved. // // #import <UIKit/UIKit.h>@interface LianxianDrawView : UIView@end
lianXianDrawView.m


// // LianxianDrawView.m // Ubbsz // // Created by 夏遠全 on 2018/2/9. // Copyright ? 2018年 beijing. All rights reserved. // #import "LianxianDrawView.h" #import "LianXianHeader.h"@interface LianxianDrawView() {NSMutableArray *pointArray; //存儲當前的一對坐標,起始點和終止點NSMutableArray *lineArray; //存儲全部的連線,每一條連線就是一對坐標NSString *startPointString; //當前起點NSString *endPointString; //當前起點 CGFloat lineWidth; }@end@implementation LianxianDrawView//對進行重寫,以便在視圖初始化的時候創建并設置自定義的Context - (id)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame]) {[self setupDefaultValue];[self regesterNotification];}return self; }//初始值 - (void)setupDefaultValue{pointArray=[[NSMutableArray alloc]init];lineArray=[[NSMutableArray alloc]init];lineWidth = 2.0f;self.backgroundColor = [UIColor colorWithRed:238/255.0 green:243/255.0 blue:248/255.0 alpha:1]; }//注冊通知 - (void)regesterNotification{[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toucheBegin:) name:kBeginPositionNotification object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toucheEnd:) name:kEndPositionNotification object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearLine:) name:kClearAllLineNotification object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freshNeedsDisplay:) name:kFreshDrawLineNotification object:nil]; }//對drawRect進行重寫 - (void)drawRect:(CGRect)rect {//獲取當前上下文,CGContextRef context=UIGraphicsGetCurrentContext();CGContextBeginPath(context);CGContextSetLineWidth(context, lineWidth);//線條拐角樣式,設置為平滑 CGContextSetLineJoin(context,kCGLineJoinRound);//線條開始樣式,設置為平滑 CGContextSetLineCap(context, kCGLineCapRound);//查看lineArray數組里是否有線條,有就將之前畫的重繪,沒有只畫當前線條if ([lineArray count] > 0) {for (int i=0; i < [lineArray count]; i++) {NSArray * array=[NSArray arrayWithArray:[lineArray objectAtIndex:i]];if ([array count] > 0 && [array count]%2 == 0) {CGContextBeginPath(context);CGPoint myStartPoint = CGPointFromString(array.firstObject);CGContextMoveToPoint(context, myStartPoint.x, myStartPoint.y);CGPoint myEndPoint = CGPointFromString(array.lastObject);CGContextAddLineToPoint(context, myEndPoint.x,myEndPoint.y);CGContextSetStrokeColorWithColor(context,[[UIColor grayColor] CGColor]);CGContextSetLineWidth(context, lineWidth);CGContextStrokePath(context);}}} }//接收起點按鈕點擊通知事件 - (void)toucheBegin:(NSNotification *)notification{CGRect beginFrame = [notification.object CGRectValue];CGPoint startPoint = CGPointMake(CGRectGetMaxX(beginFrame), CGRectGetMidY(beginFrame));startPointString = NSStringFromCGPoint(startPoint);if (pointArray.count==0) {[pointArray addObject:startPointString];}else{[pointArray replaceObjectAtIndex:0 withObject:startPointString];} }//接收終點按鈕點擊通知事件 - (void)toucheEnd:(NSNotification *)notification{CGRect endFrame = [notification.object CGRectValue];CGPoint endPoint = CGPointMake(CGRectGetMinX(endFrame), CGRectGetMidY(endFrame));endPointString = NSStringFromCGPoint(endPoint);if (pointArray.count==2) {[pointArray replaceObjectAtIndex:1 withObject:endPointString];}else{[pointArray addObject:endPointString];}[self clearSomeHistoryLineView];[self addLA];[self setNeedsDisplay]; }//接收清除按鈕點擊通知事件 - (void)clearLine:(NSNotification *)notification{[self clearAllLineView]; }//接收重新繪制通知事件 - (void)freshNeedsDisplay:(NSNotification *)notification{NSArray *relationslineArray = notification.object;lineArray = [NSMutableArray arrayWithArray:relationslineArray];[self setNeedsDisplay]; }//添加連線 -(void)addLA{NSArray *array = [NSArray arrayWithArray:pointArray];[lineArray addObject:array];[pointArray removeAllObjects]; }//清除所有的連線 - (void)clearAllLineView {[pointArray removeAllObjects];[lineArray removeAllObjects];[self setNeedsDisplay]; }//移除歷史交叉重復的連線 - (void)clearSomeHistoryLineView{NSMutableArray *arrayM = [NSMutableArray array];for (int i=0; i < [lineArray count]; i++) {NSArray *array = [NSArray arrayWithArray:[lineArray objectAtIndex:i]];if ([array count] > 0) {NSString *hisBePointString = array.firstObject;NSString *hisEnPointString = array.lastObject;if ([startPointString isEqualToString:hisBePointString] || [endPointString isEqualToString:hisEnPointString]) {[arrayM addObject:array];}}}[lineArray removeObjectsInArray:arrayM]; }//移除通知 -(void)dealloc{[[NSNotificationCenter defaultCenter] removeObserver:self]; }@end
?
(4)計算尺寸
LianXianFrameUitity.h


// // LianXianSizeUitity.h // LianxianDemo // // Created by 夏遠全 on 2018/2/9. // Copyright ? 2018年 beijing. All rights reserved. // #import <Foundation/Foundation.h> #import "LianXianModel.h"@interface LianXianFrameUitity : NSObject+ (CGRect)calculateSizeWithModel:(LianXianModel *)lianxianModel;@end
LianXianFrameUitity.m?


// // LianXianSizeUitity.m // LianxianDemo // // Created by 夏遠全 on 2018/2/9. // Copyright ? 2018年 beijing. All rights reserved. // #import "LianXianFrameUitity.h" #import "LianXianHeader.h"@implementation LianXianFrameUitity+ (CGRect)calculateSizeWithModel:(LianXianModel *)lianxianModel{NSUInteger questionsCount = lianxianModel.questions.count;NSUInteger optionsCount = lianxianModel.options.count;CGFloat LHeight = questionsCount * (BHeight+Lpadding) + Lpadding;CGFloat RHeight = optionsCount * (BHeight+Rpadding) + Rpadding;CGFloat kWidth = [UIScreen mainScreen].bounds.size.width; //默認寬度為屏幕的寬return CGRectMake(0, 0, kWidth, MAX(LHeight, RHeight)); }@end
?
(5)創建組件
LianXianComponentsView.h


// // LianXianComponentsView.h // LianxianDemo // // Created by 夏遠全 on 2018/2/6. // Copyright ? 2018年 beijing. All rights reserved. // #import <UIKit/UIKit.h> #import "LianXianModel.h"@interface LianXianComponentsView : UIView @property (nonatomic, strong) LianXianModel *lianxianModel; @end
LianXianComponentsView.m


// // LianXianComponentsView.m // LianxianDemo // // Created by 夏遠全 on 2018/2/6. // Copyright ? 2018年 beijing. All rights reserved. // #import "LianXianComponentsView.h" #import "LianxianDrawView.h" #import "LianXianHeader.h"@interface LianXianComponentsView() {NSMutableArray *_leftBtns;NSMutableArray *_rightBtns;UIButton *currentLeftBtn;CGFloat borderWith; }@end@implementation LianXianComponentsView//對進行重寫,以便在視圖初始化的時候創建并設置自定義的Context - (id)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame]) {[self setupDefalutValue];}return self; }//設置默認值 - (void)setupDefalutValue{self.backgroundColor = [UIColor clearColor];borderWith = 2.5;[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restStatus:) name:kClearAllLineNotification object:nil]; }//接收模型 -(void)setLianxianModel:(LianXianModel *)lianxianModel{_lianxianModel = lianxianModel;[self setupLianXianUnit];if (lianxianModel && lianxianModel.relationships.count>0) {[self showLianXianResult];}else{[self listClickLeftButton];} }//繪制連線選項 - (void)setupLianXianUnit{_leftBtns = [[NSMutableArray array] init];_rightBtns = [[NSMutableArray array] init];CGFloat kWidth = self.frame.size.width;CGFloat kHeight = self.frame.size.height;CGFloat LY = (kHeight-(BHeight+Lpadding)*(self.lianxianModel.questions.count-1) - BHeight)/2;CGFloat RY = (kHeight-(BHeight+Rpadding)*(self.lianxianModel.options.count-1) - BHeight)/2;for (NSInteger i =0; i < self.lianxianModel.questions.count; i++) {UIButton *btn = [self createButtonWithFrame:CGRectMake(margin, LY+(BHeight+Lpadding)*i, BWidth, BHeight) title:[NSString stringWithFormat:@"%@",self.lianxianModel.questions[i]] tag:i];[self addSubview:btn];[_leftBtns addObject:btn];}for (NSInteger i =0; i< self.lianxianModel.options.count; i++) {UIButton *btn = [self createButtonWithFrame:CGRectMake(kWidth-margin-BWidth, RY+(BHeight+Rpadding)*i, BWidth, BHeight) title:[NSString stringWithFormat:@"%@",self.lianxianModel.options[i]] tag:i];[self addSubview:btn];[_rightBtns addObject:btn];} }-(UIButton *)createButtonWithFrame:(CGRect)frame title:(NSString *)title tag:(NSInteger)tag{UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];btn.frame = frame;btn.layer.cornerRadius = 5.0;btn.layer.borderColor = [UIColor lightGrayColor].CGColor;btn.layer.borderWidth = borderWith;btn.layer.masksToBounds = YES;btn.tag = tag;[btn setBackgroundImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];[btn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:138/255.0 green:193/255.0 blue:211/255.0 alpha:1]] forState:UIControlStateHighlighted];[btn setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:138/255.0 green:193/255.0 blue:211/255.0 alpha:1]] forState:UIControlStateSelected];[btn addTarget:self action:@selector(tapBtn:) forControlEvents:UIControlEventTouchUpInside];[btn setTitle:title forState:UIControlStateNormal];[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];return btn; }- (UIImage *)imageWithColor:(UIColor *)color {CGFloat imageW = 20;CGFloat imageH = 20;UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);[color set];UIRectFill(CGRectMake(0, 0, imageW, imageH));UIImage *image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();return image; }-(void)tapBtn:(UIButton *)btn{//判斷左邊按鈕是否處于選擇狀態,只有首先左邊處于此狀態下,右邊的按鈕點擊才能進行連線操作(當前僅支持單向連線)if ([_rightBtns containsObject:btn]) {BOOL isLeftBtnSelected = NO;for (UIButton *leftBtn in _leftBtns) {if (leftBtn.selected) {isLeftBtnSelected = YES;break;}}if (!isLeftBtnSelected) {return;}}if ([_leftBtns containsObject:btn]) {//設置連線起點currentLeftBtn.selected = NO;currentLeftBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;btn.selected = YES;currentLeftBtn = btn;currentLeftBtn.layer.borderColor = [UIColor colorWithRed:32/255.0 green:199/255.0 blue:251/255.0 alpha:1].CGColor;//設置終點按鈕可以選中狀態for (UIButton *rightBtn in _rightBtns) {rightBtn.layer.borderColor = [UIColor colorWithRed:32/255.0 green:199/255.0 blue:251/255.0 alpha:1].CGColor;}//發送起點通知[[NSNotificationCenter defaultCenter] postNotificationName:kBeginPositionNotification object:[NSValue valueWithCGRect:btn.frame]];}if ([_rightBtns containsObject:btn]) {for (UIButton *leftBtn in _leftBtns) {if (leftBtn.selected) {//發送終點通知[[NSNotificationCenter defaultCenter] postNotificationName:kEndPositionNotification object:[NSValue valueWithCGRect:btn.frame]];//自動設置起始選擇按鈕 [self listClickLeftButton];break;}}} }//自動設置起始選擇按鈕 - (void)listClickLeftButton{if (!currentLeftBtn) {[self tapBtn:_leftBtns[0]];return;}NSUInteger tag = currentLeftBtn.tag;if (tag < _leftBtns.count-1) { //自動下移[self tapBtn:_leftBtns[tag+1]];}else{[self tapBtn:_leftBtns[0]]; //重新開始 } }//繪制默認已經連線的選項,此處僅僅做成績預覽使用,不能再編輯 - (void)showLianXianResult{for (UIButton *leftBtn in _leftBtns) {leftBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;leftBtn.selected = leftBtn.userInteractionEnabled = NO;}for (UIButton *rightBtn in _rightBtns) {rightBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;rightBtn.selected = rightBtn.userInteractionEnabled = NO;}if (self.lianxianModel.relationships.count == 0) {return;}NSMutableArray *relationslineArray = [NSMutableArray array];for (NSString *result in self.lianxianModel.relationships) {NSString *question = [[result componentsSeparatedByString:@"-"] firstObject];NSString *option = [[result componentsSeparatedByString:@"-"] lastObject];NSMutableArray *pointArray = [NSMutableArray array];for (UIButton *leftBtn in _leftBtns) {if ([leftBtn.currentTitle isEqualToString:question]) {CGPoint startPoint = CGPointMake(CGRectGetMaxX(leftBtn.frame), CGRectGetMidY(leftBtn.frame));NSString *startPointString = NSStringFromCGPoint(startPoint);[pointArray addObject:startPointString];break;}}for (UIButton *rightBtn in _rightBtns) {if ([rightBtn.currentTitle isEqualToString:option]) {CGPoint endPoint = CGPointMake(CGRectGetMinX(rightBtn.frame), CGRectGetMidY(rightBtn.frame));NSString *endPointString = NSStringFromCGPoint(endPoint);[pointArray addObject:endPointString];break;}}[relationslineArray addObject:pointArray];}if (relationslineArray.count > 0) {[[NSNotificationCenter defaultCenter] postNotificationName:kFreshDrawLineNotification object:relationslineArray];} }//重置初始狀態 - (void)restStatus:(NSNotification *)notification{for (UIButton *leftBtn in _leftBtns) {leftBtn.selected = NO;leftBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;[self tapBtn:_leftBtns[0]]; //重新開始 } }@end
?
(6)連線容器
LianXianContainerView.h


// // LianXianContainerView.h // LianxianDemo // // Created by 夏遠全 on 2018/2/8. // Copyright ? 2018年 beijing. All rights reserved. // #import <UIKit/UIKit.h> #import "LianXianComponentsView.h" #import "LianxianDrawView.h"@interface LianXianContainerView : UIView @property (nonatomic, strong) LianXianComponentsView *componentsView; @property (nonatomic, strong) LianxianDrawView *lianXianView; @end
LianXianContainerView.m


// // LianXianContainerView.m // LianxianDemo // // Created by 夏遠全 on 2018/2/8. // Copyright ? 2018年 beijing. All rights reserved. // #import "LianXianContainerView.h" #import "LianXianComponentsView.h" #import "LianxianDrawView.h" #import "LianXianModel.h"@implementation LianXianContainerView- (id)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame]) {[self setup];}return self; }- (void)setup{self.lianXianView = [[LianxianDrawView alloc]initWithFrame:self.bounds];self.componentsView = [[LianXianComponentsView alloc] initWithFrame:self.bounds];[self addSubview:self.lianXianView];[self addSubview:self.componentsView]; }@end
?
(7)顯示連線


// // ViewController.m // LianxianDemo // // Created by tianjing on 15/3/31. // Copyright ? 2015年 tianjing. All rights reserved. // #import "ViewController.h"#import "LianXianContainerView.h" #import "LianXianFrameUitity.h" #import "LianXianModel.h" #import "LianXianHeader.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];UIButton *clearBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 100, 40)];clearBtn.backgroundColor = [UIColor greenColor];[clearBtn setTitle:@"重置" forState:UIControlStateNormal];[clearBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];[clearBtn addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];//創建模型LianXianModel *lianxianModel = [[LianXianModel alloc] init];lianxianModel.questions = @[@"天",@"好",@"人"]; /// 左邊選項lianxianModel.options = @[@"夏",@"世",@"鋒"]; /// 右邊選項//lianxianModel.relationships = @[@"天-世",@"好-夏",@"人-鋒"]; /// 連線關系,如果不為空,就只顯示,不能編輯//clearBtn.hidden = (lianxianModel.relationships.count>0);//連線視圖CGRect frame = [LianXianFrameUitity calculateSizeWithModel:lianxianModel];LianXianContainerView *containerView = [[LianXianContainerView alloc] initWithFrame:frame];containerView.center = self.view.center;containerView.componentsView.lianxianModel = lianxianModel;[self.view addSubview:containerView];[self.view addSubview:clearBtn]; }- (void)clear:(UIButton *)sender{[[NSNotificationCenter defaultCenter] postNotificationName:kClearAllLineNotification object:nil]; }@end
?
四、效果
提示:
左邊按鈕每次只有一個處于可連狀態,而且每一次連接完會循環自動下移。
右邊所有按鈕始終處于可連狀態。
同一個按鈕再一次連接新的連線后,之前舊的跟其相關的連線都會被取消。?
?
??
?
五、采坑
如果練習題的界面是放在cell中的,因為復用的問題,在發送起點和終點的通知時,要對通知做唯一標識處理。
如果不這么做,可能會出現的bug是:上一道做過的連線題的連線會出現在下一道還沒有做過的連線題上。
?