Xcode: Remove an array of textiews from screen - ios

I'm currently adding 5 textviews onto the viewcontroller programatically inside the viewDidLoad method.
for (int i = 0; i < 5; i++) {
//Add 5 textviews
UITextView *reqTV = [[UITextView alloc] initWithFrame:CGRectMake(30,30,250,50)];
reqTV.text = #"This is a textview";
[self.view addSubview:reqTV];
}
If later, I want to delete (not hide) these 5 textviews with a button click, how would I do that?
I have thought of using this, but am not sure how to call all 5 textviews to delete them.
- (void)removeTextViewButton:(id)sender {
[reqTV removeFromSuperview]; //remove textview
}
Thank you.

I see two easy ways:
You can save your textViews inside array as ivar of your controller.
And later remove each textView in array.
for (int i = 0; i < 5; i++) {
...
[textViews addObject: reqTV];
...
}
- (void)removeTextViewButton:(UIButton *)sender {
[textViews makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
2. Assign static tag for each textView:
for (int i = 0; i < 5; i++) {
...
reqTV.tag = 1001; // for example
}
- (void)removeTextViewButton:(UIButton *)sender {
NSArray *subs = [NSArray arrayWithArray: self.view.subviews];
for (UIView *sub in subs) {
if (sub.tag == 1001) {
[sub removeFromSuperview];
}
}
}

Used code below to remove UITextViews:
- (void)removeTextViewButton:(id)sender {
NSArray *reqTVViews = [NSArray arrayWithArray: self.view.subviews];
for (UIView *tvView in reqTVViews) {
if ([tvView isKindOfClass:[UITextView class]]) {
[tvView removeFromSuperview];
}
}
}

When you are adding UITextFields on viewController use tag value to uniquely identify each textField.
You can store each tag value in an array for further use, eg.
#property (nonatomic, strong) NSMutableArray *tagArray;
NSMutableArray *tagArray = [NSMutableArray array];
for (int i = 101; i <= 105; i++ ) {
UITextField *txt = [UITextField alloc] init]; //for eg.
...
...
txt.tag = i;
[arr addObject:[NSNumber numberWithInt:i]];
[self.view addSubView:txt];
}
When you want to delete any of the textField or all then...
UIView *view = [self.view viewWithTag:<tag value>];
[view removeFromSuperview];
eg.
for (int i = 0; i < tagArray.count; i++) {
NSInteger tag = [[arr objectAtIndex:i] intValue];
UITextField *txt = (UITextField *)[self.view viewWithTag:tag];
[txt removeFromSuperview];
}

You can remove all subview in one go
- (void)removeTextViewButton:(id)sender
{
for (UIView *subview in views.subviews)
{
[subview removeFromSuperview];
}
}
Happy Coding.. :)

Related

How to change multiple UILabel text colour while scrolling inside scrollview Objective-c iOS

Hi I am new to iOS development..Can any one help me..
I have added multiple UILabel inside UIScrollview based on array count..For example if array count is 3 means ..then In scrollview adding 3 view along with UILabel in each view..
So now 3 view having 3 different UILabels..
But now I want to change colour of UILabel text in different views based on requirement..but I am not able to update colour…
Its change colour of UILabel text only for last index ..
I have written code in ScrollViewDidScroll:(UIScrollView *)scrollView
Any suggestion ..
self.robotScrollView.contentSize = CGSizeMake(robotCounts*Robot_ScrollView_Width, kRobotSrollViewH);
for (int i=0; i<robotCounts; i++) {
self.robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
self.robotLabel.textAlignment = NSTextAlignmentCenter;
self.robotLabel.backgroundColor = [UIColor clearColor];
self.robotLabel.textColor = [UIColor blackColor];
[self.robotScrollView addSubview:self.robotLabel];
if (kRemoteManager.robotsArray.count == 0) {
self.robotLabel.text = #"";
break;
}
DeviceBase *robot = kRemoteManager.robotsArray[i];
self.robotLabel.text = [NSString stringWithFormat:#"%#",robot.dName];
}
self.robotScrollView.contentOffset = CGPointMake(Robot_ScrollView_Width*currentRobotIndex, 0);
Changing UIlabeltext color in below scrollviewdidscroll method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.scrollView)
{
self.pageControl.currentPage = (scrollView.contentOffset.x+(scrollView.width/2)) / scrollView.width;
kRemoteManager.currentIndex = self.pageControl.currentPage;
[[NSNotificationCenter defaultCenter] postNotificationName:kNotify_Steward_ReloadData object:nil];
NSMutableArray *viewRemoteIDarray = [NSMutableArray array];
CardRemoteModel *model = kRemoteManager.cardRemoteArray[self.pageControl.currentPage];
if (![viewRemoteIDarray containsObject:#(model.remoteID)])
{
if (model.remoteType == kooKong_remoteType_AirCleaner || model.remoteType == kooKong_remoteType_AC)
{
self.robotLabel.textColor = [UIColor whiteColor];
}
else
{
self.robotLabel.textColor = [UIColor blackColor];
}
}
} else if (scrollView == self.robotScrollView) {
kRemoteManager.currentRobotIndex = (scrollView.contentOffset.x+(scrollView.width/2)) / scrollView.width;
self.leftBtn.hidden = NO;
self.rightBtn.hidden = NO;
if (kRemoteManager.currentRobotIndex == kRemoteManager.robotsArray.count-1) {
self.rightBtn.hidden = YES;
}
if (kRemoteManager.currentRobotIndex == 0){
self.leftBtn.hidden = YES;
}
}
}
There are three labels, but only one label property. The last one assigned is the only one you'll have access to later. One solution would be to keep an array of labels in the view controller.
#property(nonatomic, strong) NSMutableArray *labels;
In the posted method...
self.labels = [NSMutableArray array];
for (int i=0; i<robotCounts; i++) {
UILabel *robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
[self.labels addObject:robotLabel]; // <--- new
robotLabel.textAlignment = NSTextAlignmentCenter;
robotLabel.backgroundColor = [UIColor clearColor];
robotLabel.textColor = [UIColor blackColor];
[self.robotScrollView addSubview:robotLabel];
if (kRemoteManager.robotsArray.count == 0) {
robotLabel.text = #"当前无酷控机器人";
break;
}
DeviceBase *robot = kRemoteManager.robotsArray[i];
robotLabel.text = [NSString stringWithFormat:#"%#",robot.dName];
}
To change all of the colors:
- (void)setLabelColors:(UIColor *)color {
for (UILabel *label in self.labels) {
label.textColor = color;
}
}
Another idea would be to give each label a tag, and find them when you need them.
for (int i=0; i<robotCounts; i++) {
self.robotLabel = [[UILabel alloc] initWithFrame:CGRectMake(Robot_ScrollView_Width*i, 0 , Robot_ScrollView_Width, kRobotSrollViewH)];
self.robotLabel.tag = i+1;
// the remainder of this loop as you have it
To change all the colors...
- (void)setLabelColors:(UIColor *)color {
for (int i=0; i<robotCounts; i++) {
UILabel *label = (UILabel *)[self.robotScrollView viewWithTag:i+1];
label.textColor = color;
}
}

Reload UIScrollView by tapping a UIButton

Let me explain my project first. I have some data in my SQLIte DB table called "note".
In "note" table I have these fields: id, noteToken, note.
What I am doing here is load all the note in an NSMUtableArray from that table. And create UIButton according to that array content number and add those buttons in a UIScrollView as subView. The number of buttons and width of scrollview generate auto according to the number of content of that array. Now, when some one tap one of those Buttons, it will bring him to a next viewController and show him the corresponding note details in that viewController.
I do the same thing with another NSMUtableArray, but these time it read all the id from the "note" table. It equally generate new delete button in the same UIScrollView. But if some one tap on these delete button it will delete that particular note from the table "note" of SQLIte DB. AND RELOAD THE UIScrollView. All are done except the RELOAD THE UIScrollView part. This is what I want. I tried with all exist solution but don't know why it's not working.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.noteToken = [NSString stringWithFormat:#"%#%#", fairId, exibitorId];
scrollViewNoteWidth = 100;
[scrollViewNote setScrollEnabled:YES];
[scrollViewNote setContentSize:CGSizeMake((noteButtonWidth * countNoteButtonArray) + scrollViewNoteWidth, 100)];
sqLite = [[SQLite alloc] init];
[self.sqLite callDataBaseAndNoteTableMethods];
self.noteButtonArrayy = [[NSMutableArray alloc] init];
noteButtonArrayy = [self.sqLite returnDataFromNoteTable:noteToken];
[self LoadNoteButtonAndDeleteButton:noteButtonArrayy];
}
//////////////*----------------------- Note Section (Down) -----------------------*//////////////
-(void) LoadNoteButtonAndDeleteButton:(NSMutableArray *) noteButtonArray
{
sQLiteClass = [[SQLiteClass alloc] init];
noteButtonArrayToShowNoteButton = [[NSMutableArray alloc] init];
/*--------------- Load the noteButton & pass note (Down)---------------*/
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
NSString *nt = sQLiteClass.note;
[noteButtonArrayToShowNoteButton addObject:nt];
}
[self ShowNoteButtonMethod:noteButtonArrayToShowNoteButton];
/*--------------- Load the noteButton & pass note (Up)---------------*/
/*--------------- Load the deleteButton & pass id (Down)---------------*/
noteButtonArrayToDeleteNoteButton = [[NSMutableArray alloc] init];
for (int i = 0; i < [noteButtonArray count]; i++)
{
sQLiteClass = [noteButtonArray objectAtIndex:i];
// Convert int into NSString
NSString *ids = [NSString stringWithFormat:#"%d", sQLiteClass.idNum];
[noteButtonArrayToDeleteNoteButton addObject:ids];
}
[self ShowNoteDeleteButtonMethod:noteButtonArrayToDeleteNoteButton];
/*--------------- Load the deleteButton & pass id (Down)---------------*/
}
-(void) ShowNoteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For note button
noteButtonWidth = 60;
noteButtonXposition = 8;
for (NSString *urls in btnarray)
{
noteButtonXposition = [self addNoteButton:noteButtonXposition AndURL:urls];
}
}
-(int) addNoteButton:(int) xposition AndURL:(NSString *) urls
{
noteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
noteButton.frame = CGRectMake(noteButtonXposition, 8.0, noteButtonWidth, 60.0);
[noteButton setImage:[UIImage imageNamed:#"note.png"] forState:UIControlStateNormal];
[noteButton addTarget:self action:#selector(tapOnNoteButton:) forControlEvents:UIControlEventTouchUpInside];
[noteButton setUrl:urls];
noteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:noteButton];
noteButtonXposition = noteButtonXposition + noteButtonWidth + 18;
return noteButtonXposition;
}
-(void)tapOnNoteButton:(ButtonClass*)sender
{
urlNote = sender.url;
[self performSegueWithIdentifier:#"goToNoteDetailsViewController" sender:urlNote];
}
-(void) ShowNoteDeleteButtonMethod:(NSMutableArray *) btnarray
{
countNoteButtonArray = [btnarray count];
// For delete button
deleteNoteButtonWidth = 14;
deleteNoteButtonXposition = 31;
for (NSString *idNumber in btnarray)
{
deleteNoteButtonXposition = [self addDeleteButton:deleteNoteButtonXposition AndURL:idNumber];
}
}
-(int) addDeleteButton:(int) xposition AndURL:(NSString *) idNumber
{
deleteNoteButton =[ButtonClass buttonWithType:UIButtonTypeCustom];
deleteNoteButton.frame = CGRectMake(deleteNoteButtonXposition, 74.0, deleteNoteButtonWidth, 20.0);
[deleteNoteButton setImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[deleteNoteButton addTarget:self action:#selector(tapOnDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[deleteNoteButton setIdNum:idNumber];
deleteNoteButton.backgroundColor = [UIColor clearColor];
[self.scrollViewNote addSubview:deleteNoteButton];
deleteNoteButtonXposition = deleteNoteButtonXposition + deleteNoteButtonWidth + 65;
return deleteNoteButtonXposition;
}
-(void)tapOnDeleteButton:(ButtonClass*)sender
{
idNumb = sender.idNum;
[self.sqLite deleteData:[NSString stringWithFormat:#"DELETE FROM note WHERE id IS '%#'", idNumb]];
// NSLog(#"idNumb %#", idNumb);
//[self.view setNeedsDisplay];
//[self.view setNeedsLayout];
//[self LoadNoteButtonAndDeleteButton];
//[self viewDidLoad];
// if ([self isViewLoaded])
// {
// //self.view = Nil;
// //[self viewDidLoad];
// [self LoadNoteButtonAndDeleteButton];
// }
}
//////////////*----------------------- Note Section (Up) -----------------------*//////////////
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"goToNoteDetailsViewController"])
{
NoteDetailsViewController *noteDetailsViewController = [segue destinationViewController];
[noteDetailsViewController setUrl:sender];
}
}
Here's the screen shot:
Here we can feel the difference between UIScrollView and UICollectionView, however UICollectionView is made up of UIScrollView, UICollectionView can be reload and adjust its content accordingly, where UIScrollView can't.
Ok, now in your case, you've to reload (refresh) your scroll view, which is not possible as we can with UICollectionView or UITableView.
You've two options,
Best option (little tough) : replace UIScrollView with UICollectionView - will take some of your time, but better for reducing code complexity and good performance of your app.
Poor option (easy) : Stay as it with UIScrollView - when you want to reload, delete each subview from it, and then again show and load everything. Highly not recommended.
IMHO, you should go with best option.

Get the number of switches set ON

I have this method bellow. Is there any way I can count UISwitches which are set on? Thanks!
while (i < numberOfAnswers) {
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
mySwitch.tag = i;
[_answerView addSubview:mySwitch];
i++;
}
I think that it'd be better if you keep references to switches.
NSMutableArray *switches = [NSMutableArray array]; // You can do that as property
while (i < numberOfAnswers) {
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
mySwitch.tag = i;
[_answerView addSubview:mySwitch];
i++;
[switches addObject:mySwitch];
}
Then later you don't have to iterate through every subview in view but you can iterate just switches array.
int count = 0;
for (UISwitch *switch in switches)
{
if (switch.isOn)
{
count += 1;
}
}
I like Piotr's solution, but if you really just want to know how many switches are on, you can also add this line to your initialization loop:
[mySwitch addTarget:self action:#selector(switchValueDidChange:) forControlEvents:UIControlEventValueChanged];
add a property to your class:
#property (nonatomic) int onCounts
And then this method:
-(void)switchValueDidChange:(UISwitch)sender {
self.onCounts = sender.on ? self.onCounts + 1 : self.onCounts - 1;
}
Now you can access the onCount property at any time to know how many switches are on.
Try
int count = 0;
for (UIView *subview in _answerView.subviews) {
if ([subview isKindOfClass:[UISwitch class]]) {
UISwitch *sw = (UISwitch*)subview;
count += sw.isOn ? 1 : 0;
}
}
here your code
int count = 0;
for (int i = start_switch_tag;i< numberOfAnswers;i++) {
if (((UISwitch *)[_answerView viewWithTag:i]).isOn) count ++;
}
NSLog(#"number of switches set ON: %d", count);

UIView is not removed from superview

I`m having problem with removing view from superview.
Adding view:
- (void)createCircles
{
NSString *currentDate = [self currentDate];
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = nil;
for (label in array)
{
if ([label.text isEqualToString:currentDate])
{
UIView *view = [[UIView alloc] initWithFrame:label.frame];
view.backgroundColor = [UIColor redColor];
[self.horizontalScroll insertSubview:view atIndex:0];
[self.labelsArray insertObject:view atIndex:0];
}
}
}
Trying to remove:
- (void)labelTouch:(UITapGestureRecognizer*)sender
{
NSArray *array = [self.horizontalScroll subviews];
UILabel *label = (UILabel*)sender.view;
for (int i = 0; i < [array count]; ++i)
{
UILabel *l = array[i];
if (label.tag == l.tag)
{
UIView *view = nil;
view = [self.labelsArray objectAtIndex:0];
view.hidden = YES;
[view removeFromSuperview];
view = nil;
[self.labelsArray removeObjectAtIndex:0];
}
}
}
But after touch view is still displaying. Tried to remove label (l) - it is removed
Try this,
[[[self.horizontalScroll subviews] objectAtIndex:0] removeFromSuperView];
You should store reference to this "unkillable" view in ivar or property. Initialize it in first method and call removeFromSupperView in second.

Return position in NSArray from ScrollView

I'm trying to create a scrollview with an array of clickable UIImageView's. My goal is that when an ImageView is clicked, it returns which position in the array it occupies. The problem is that i don't know how to "catch" the position's number. How do I do that?
So far I have:
- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer {
NSLog(#"%#",)//here is where i want to return the element's position.
}
-(void) preenchemenu {
[menu setContentSize:CGSizeMake(400, 91)];
int x=0;
imagensmenu=[NSArray arrayWithObjects:[UIImage imageNamed:#"teste2.tiff"],[UIImage imageNamed:#"teste2.tiff"], nil];
for (int i = 0; i <3; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x,0 , 90, 91)];
x=x+90;
imageView.image = [imagensmenu objectAtIndex:i];
imageView.tag = 1000+ i;
imageView.userInteractionEnabled = YES;
imageView.multipleTouchEnabled = YES;
UITapGestureRecognizer *tapRecognizermenu = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(respondToTapGesture:)];
tapRecognizermenu.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:tapRecognizermenu];
[menu addSubview:imageView];
}
}
You can create an array to hold you imageViews and then find the position of your imageView in this array when it is tapped.
Add a property for this
#property (nonatomic, strong) NSMutableArray *imageViews;
initialise it in init
- (id)init...
{
self = [super init...
if (self) {
_imageViews = [NSMutableArray array];
}
return self;
}
Then amend your current method slightly to also add the imageViews to this array as well as a subview of the menu
[self.imageViews addObject:imageView];
[menu addSubview:imageView];
Then in your gesture recognizer call back you can do
- (void)respondToTapGesture:(id)sender;
{
UIView *view = [sender view];
NSLog(#"%d", [self.imageViews indexOfObject:view]);
}
Just find the index by
- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer
{
UIView *view = recognizer.view;
NSLog(#"Index of image in array is %d", view.tag-1000);
}

Resources