问题描述
- 通过编程创建多个复选框
-
在UIViewController
中有一个UITextView
,要对UITextView插入多个复选框。怎么创建多个复选框,并且对这些复选框动态的创建方法?
目前代码如下:
-(void)Check { CGPoint origin = note.frame.origin; NSString* head = [note.text substringToIndex:note.selectedRange.location]; CGSize initialSize = [head sizeWithFont:note.font constrainedToSize:note.contentSize]; NSUInteger startOfLine = [head length]; NSString* tail = [head substringFromIndex:startOfLine]; CGSize lineSize = [tail sizeWithFont:note.font forWidth:note.contentSize.width lineBreakMode:UILineBreakModeWordWrap]; CGPoint cursor = origin; cursor.x += lineSize.width+15; cursor.y += initialSize.height - lineSize.height-130; checkbox = [[UIButton alloc] initWithFrame:CGRectMake(cursor.x,cursor.y,15,15)]; [checkbox setBackgroundImage:[UIImage imageNamed:@"unchk.png"]forState:UIControlStateNormal]; [checkbox setBackgroundImage:[UIImage imageNamed:@"chk.png"]forState:UIControlStateSelected]; [checkbox setBackgroundImage:[UIImage imageNamed:@"chk.png"]forState:UIControlStateHighlighted]; checkbox.adjustsImageWhenHighlighted=YES; [checkbox addTarget:self action:@selector(ChkUnChk) forControlEvents:UIControlEventTouchUpInside]; [note addSubview:checkbox]; } -(void)ChkUnChk { if(checkUnCheck==NO) { [checkbox setBackgroundImage:[UIImage imageNamed:@"chk.png"]forState:UIControlStateNormal]; checkUnCheck=YES; } else if(checkUnCheck==YES) { [checkbox setBackgroundImage:[UIImage imageNamed:@"unchk.png"]forState:UIControlStateNormal]; checkUnCheck=NO; } } -(void)checkboxSelected:(id)sender { checkBoxSelected = !checkBoxSelected; [checkbox setSelected:checkBoxSelected]; }
其中note --> UITextView,checkbox --> UIButton
解决方案
用NSMutableArray
.h文件
NSMutableArray *selectedBtnarr;
.m文件
- (void)viewDidLoad
{
selectedBtnarr=[NSMutableArray alloc]init];
}
然后设置 UIButton的属性. 每个Button都有不同标签.
-(void)ChkUnChk:(id)sender
{
UIButton *btn=(UIButton *)sender;
NSString *Str=[NSString stringWithFormat:@"%d",btn.tag];
BOOL flag= [selectedBtnarr containsObject:Str];
if (flag==YES)
{
[btn setBackgroundImage:[UIImage imageNamed:@"unchk.png"] forState:UIControlStateNormal];
[selectedBtnarr removeObject:Str];
}
else
{
[selectedBtnarr addObject:Str];
[btn setBackgroundImage:[UIImage imageNamed:@"chk.png"] forState:UIControlStateNormal];
}
}
时间: 2024-11-04 16:42:53