2016-06-19 3 views
0

Когда я перемещаю вид коллекции по экрану, весь контроллер просмотра снова перезагружается. Это означает, что все анимации, которые произошли ранее, должны повториться. Есть ли способ остановить перезагрузку контроллера просмотра при загрузке коллекции?Когда я прокручиваю по горизонтали через мой просмотр коллекции, весь вид перезагружает запуск анимации снова

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 


    let cell2 = CollectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! BookingDateCollectionCellClass 

    let later = getDate(indexPath.row + 5).day 
    print(later) 


    let date: String = String(later) 
    print(date) 
    cell2.dateLabel.text = date 

    let day = getDateData(indexPath.row + 5).dayOfWeek() 
    print(day) 
    cell2.dayLabel.text = dayShortFromNumber(day!) 


    return cell2 

} 

Before Start Animation After Start Animation

import UIKit 

class BookingDateVC: UIViewController, UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource { 

// Outlets 

@IBOutlet weak var tableViewDates: UITableView! 

@IBOutlet weak var CollectionView: UICollectionView! 

@IBOutlet weak var bigMonthView: UIView! 

@IBOutlet weak var selectDateLabel: UILabel! 

@IBOutlet weak var todayDateView: UIView! 

@IBOutlet weak var todayButton: UIButton! 

@IBOutlet weak var tomorrowButton: UIButton! 

@IBOutlet weak var laterButton: UIButton! 

@IBOutlet weak var plusButton: UIButton! 

@IBOutlet weak var monthView: UIView! 

@IBOutlet weak var monthLabel: UILabel! 


// Calendar Variables 
var month: Int? 
var index: NSIndexPath? 
var passData: dataReceipt? 


override func viewDidLoad() { 
    super.viewDidLoad() 

    // Table View Customerisation 
    tableViewDates.backgroundColor = UIColor(red: 38/255, green: 163/255, blue: 133/255, alpha: 1) 
    self.tableViewDates.center.y += self.view.bounds.height 

} 

override func viewDidAppear(animated: Bool) { 

    // Sets up inital dates - Today, Tomorrow, Later 
    let today = getDate(0).day 
    let tomorrow = getDate(1).day 
    let later = getDate(2).day 

    todayButton.setTitle(String(today), forState: .Normal) 
    tomorrowButton.setTitle(String(tomorrow), forState: .Normal) 
    laterButton.setTitle(String(later), forState: .Normal) 
    plusButton.setTitle("+", forState: .Normal) 


} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


@IBAction func todayButton(sender: AnyObject) { 
    passData?.data = monthFromNumber(getDate(0).month) + " " + todayButton.currentTitle! 
} 

@IBAction func tomorrowButton(sender: AnyObject) { 
    passData?.data = monthFromNumber(getDate(1).month) + " " + tomorrowButton.currentTitle! 

} 

// Gets date as components - Hour, Day, Month, Year 
func getDate(days: Int) -> NSDateComponents{ 
    let date = getDateData(days) 
    let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year] 
    let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: date) 
    return components 

} 

// Gets date + number of days from today 
func getDateData(days: Int) -> NSDate{ 
    let today = NSDate() 
    let date = NSCalendar.currentCalendar().dateByAddingUnit(
     .Day, 
     value: days, 
     toDate: today, 
     options: NSCalendarOptions(rawValue: 0)) 

    return date! 
} 

// Returns day string in full from day int 
func dayFromNumber(day: Int) -> String{ 
    switch(day){ 
    case 1: 
     return "SUNDAY" 
    case 2: 
     return "MONDAY" 
    case 3: 
     return "TUESDAY" 
    case 4: 
     return "WEDNESDAY" 
    case 5: 
     return "THURSDAY" 
    case 6: 
     return "FRIDAY" 
    case 7: 
     return "SATURDAY" 
    default: 
     return "" 
    } 
} 

// Returns day string in short from day int 
func dayShortFromNumber(day: Int) -> String{ 
    switch(day){ 
    case 1: 
     return "SUN" 
    case 2: 
     return "MON" 
    case 3: 
     return "TUE" 
    case 4: 
     return "WED" 
    case 5: 
     return "THU" 
    case 6: 
     return "FRI" 
    case 7: 
     return "SAT" 
    default: 
     return "" 
    } 
} 

// Returns month string in short from month int 
func monthFromNumber(month: Int) -> String{ 
    switch(month){ 
    case 1: 
     return "JAN" 
    case 2: 
     return "FEB" 
    case 3: 
     return "MAR" 
    case 4: 
     return "APR" 
    case 5: 
     return "MAY" 
    case 6: 
     return "JUN" 
    case 7: 
     return "JUL" 
    case 8: 
     return "AUG" 
    case 9: 
     return "SEP" 
    case 10: 
     return "OCT" 
    case 11: 
     return "NOV" 
    case 12: 
     return "DEC" 
    default: 
     return "" 
    } 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete implementation, return the number of rows 
    return 3 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableViewDates.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BookingDateCellClass 
    let later = getDate(2).day 
    let date: String = String(indexPath.row + later) 
    cell.dateLabel.text = date 

    let day = getDateData(indexPath.row + 2).dayOfWeek() 
    cell.dayLabel.text = dayFromNumber(day!) 

    let bgColorView = UIView() 
    bgColorView.backgroundColor = UIColor(red: 253/255, green: 196/255, blue: 0, alpha: 1) 
    cell.selectedBackgroundView = bgColorView 


    return cell 
} 


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! BookingDateCellClass 
    passData?.data = monthFromNumber(getDate(indexPath.row + 2).month) + " " + cell.dateLabel.text! 
    performSegueWithIdentifier("timeSegue", sender: self) 
} 




func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the specified item to be editable. 
    return false 
} 



func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{ 
    return 60.0;//Choose your custom row height 
} 




@IBAction func laterButtonFunc(sender: AnyObject) { 

    // Animates to later dates 
    UIView.animateWithDuration(0.5, animations: { 
     self.tableViewDates.center.y = self.view.frame.height/2 

     self.todayDateView.center.y = self.view.frame.height/6 
     self.monthView.center.y = (self.view.frame.height/4) * 3.25 

    }) 
} 


func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return 20 
} 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 


    let cell2 = CollectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! BookingDateCollectionCellClass 

    let later = getDate(indexPath.row + 5).day 
    let date: String = String(later) 
    cell2.dateLabel.text = date 

    let day = getDateData(indexPath.row + 5).dayOfWeek() 
    cell2.dayLabel.text = dayShortFromNumber(day!) 
    //self.monthLabel.text = monthFromNumber(getDate(indexPath.row + 5).month) 

    return cell2 

    } 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! BookingDateCollectionCellClass 
    passData?.data = monthFromNumber(getDate(indexPath.row + 5).month) + " " + cell.dateLabel.text! 
    performSegueWithIdentifier("timeSegue", sender: indexPath) 
} 


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "timeSegue" { 
     if let destination = segue.destinationViewController as? BookingTimeVC { 
      print((passData?.data)!) 
      destination.passData = passData 



     } 
    } 
} 


} 
+1

Контроллер представления не должен загружаться при перезагрузке просмотра коллекции. Если это так, это то, что вы делаете в своем коде. Вам нужно будет предоставить более подробное описание последовательности, которая запускает эту перезагрузку, включая код, который вызывается. Я предлагаю вам установить точку останова в методе, который вызывается несколько раз, и посмотреть на стек вызовов, чтобы увидеть, как он снова вызван. –

+0

Я добавил полный исходный код @DuncanC – User

ответ

0

я не заметил, что отправка не полностью выполняется. Вы касаетесь кнопки до завершения выполнения потока. Кроме того, я не думаю, что данные вызываются правильно. Должны быть отдельные вызовы для установки данных , затем перезагрузить таблицу. В качестве альтернативы вы можете сразу начать настройку данных таблицы, когда вы переходите так, когда пользователь добирается до VC, все готово. Однако я склоняюсь к тому, что это проблема отправки.

+0

Принимая это, не решает проблему @KFDoom – User

+1

Посмотрите на это сейчас. – KFDoom

+0

Это просто, когда вид коллекции перемещается в первый индекс, после чего он не перезапускает экран @KFDoom – User