2014-12-10 4 views
0

Позвольте мне сначала объяснить мой проект. У меня есть некоторые данные в моей таблице SQLIte с названием «note». В таблице «note» у меня есть следующие поля: id, noteToken, note.Обновить UIScrollView, нажав на UIButton

Что я здесь делаю, загружает все note в NSMUtableArray из этого стола. И создайте UIButton в соответствии с этим номером array и добавьте эти кнопки в UIScrollView как subView. Количество кнопок и ширина scrollview генерируют auto в соответствии с количеством содержимого этого массива. Теперь, когда кто-то коснется одной из этих кнопок, он приведет его к следующему viewController и покажет ему соответствующие примечания в этом viewController.

Я делаю то же самое с другим NSMUtableArray, но на этот раз он читает все id из таблицы «примечание». Он также генерирует новую кнопку удаления в том же UIScrollView. Но если кто-то нажат на эту кнопку удаления, он удалит это примечание из таблицы «note» из SQLIte DB. И ПЕРЕМЕЩЕНИЕ UIScrollView. Все сделано, за исключением RELOAD THE UIScrollView часть. Это то, чего я хочу. Я пробовал со всем существующим решением, но не знаю, почему он не работает.
Вот мой код:

- (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]; 
    } 
} 

Вот снимок экрана:

enter image description here

ответ

2

Здесь мы можем почувствовать разницу между UIScrollView и UICollectionView, однако UICollectionView состоит из UIScrollView, UICollectionView может быть перезагрузите и отрегулируйте его содержимое соответственно, где UIScrollView не может.

Итак, теперь в вашем случае вы должны перезагрузить (обновить) свой вид прокрутки, что невозможно, поскольку мы можем с UICollectionView или UITableView.

Вы имеете два варианта,

Лучший вариант (немного жесткий): заменить UIScrollView с UICollectionView - займет часть вашего времени, но лучше для снижения сложности кода и хорошую производительность вашего приложения.

Неудовлетворительный вариант (простой): Оставайтесь с UIScrollView - когда вы хотите перезагрузить, удалите каждый из них, а затем снова покажите и загрузите все. Не рекомендуется.

ИМХО, вы должны пойти с лучшим вариантом.

+0

Я выбрал ваш «лучший вариант», и теперь он отлично работает, как я и хотел. Это проще, быстрее и круто. :) Спасибо за комментарий. Будь здоров. :) – Tulon