2016-03-23 5 views
0

Я играю вокруг, пытаясь одушевить содержимое моей таблицы, когда оно выбрано, но у меня проблемы. Я прочитал несколько мест, в которых вы не можете запустить animatewithduration в файле didSelectRowAtIndexPath или, по крайней мере, он не оживляет, если вы это сделаете. Это похоже на код, который у меня ниже, представление движется, но не оживляет.Swift - Анимация, когда выбран TableView Cell (didSelectRowAtIndexPath)

Я попытался включить логику в willDisplayCell для контроля за выбором, но безрезультатно, и поэтому мне бы это понравилось, если кто-то сможет найти для меня правильное решение, потому что ответ, похоже, недоступен, несмотря на много исп.:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let currentCellDescriptor = getCellDescriptorForIndexPath(indexPath) 
    let cell = tableView.dequeueReusableCellWithIdentifier(currentCellDescriptor["cellIdentifier"] as! String, forIndexPath: indexPath) as! CustomCell 
    let indexOfTappedRow = visibleRowsPerSection[indexPath.section][indexPath.row] 
    if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpandable"] as! Bool == true { 
     if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == false { 


      // INTERESTING BIT: Animates cell contents to Right 
      if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" { 
       UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: { 
        cell.headerTitleLeftConstraint.priority = 999 
        cell.headerTitleRightConstraint.priority = 1 
        cell.layoutIfNeeded() 
        }, completion: nil) 
      } 

     } else if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == true { 
      // MARK: Animates cell contents back to left 
      if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" { 
       UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: { 
        cell.headerTitleLeftConstraint.priority = 1 
        cell.headerTitleRightConstraint.priority = 999 
        cell.layoutIfNeeded() 
        }, completion: nil) 
        } 
      } 
+0

Почему вы используете «пусть клетка = tableView.dequeueReusableCellWithIdentifier (currentCellDescriptor [ "cellIdentifier"], как String, forIndexPath: indexPath) как! CustomCell 'в' didSelectRowAtIndexPath '? – MrDank

+0

Г-н Вейдер, это потому, что у меня есть plist, который содержит все данные моей ячейки. Это намного проще, потому что у меня есть несколько расширяемых уровней ячеек. –

ответ

1

Во-первых, не используйте dequeueReusableCellWithIdentifier здесь. Он будет использовать ячейку, которая не видна на экране, и подготовиться к ее показу. То, что вы хотите, это cellForRowAtIndexPath, который возвращает ячейку уже на экране при заданном indexPath.

Тогда я понимаю, что вы хотите играть с 2 ограничениями и анимировать изменения макета. Для того, чтобы сделать это, анимация должна содержать только layoutIfNeeded:

cell.headerTitleLeftConstraint.priority = 999 
cell.headerTitleRightConstraint.priority = 1 
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: { 
       cell.layoutIfNeeded() 
       }, completion: nil) 

Я также советую вам перенести эту логику из контроллера в вашем CustomCell классе. Например, используйте атрибут selected и setSelected(animated: Bool) для визуального изменения состояния.

0

С помощью Tanguy, вот как мы ищем. У меня все еще есть некоторые проблемы с анимацией, потому что сама таблица не будет анимировать следующий уровень ячеек под ним, но я улучшу этот код и заработаю его. Думайте, что это подходит для цели сейчас, поэтому стоит опубликовать, чтобы показать самое решение. Благодаря!!

override func setSelected(selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 
     // Adjusts constraints everytime switch is tapped 
     isLeftAligned = !isLeftAligned 
      if userHanded == "Right" { 
      UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: { 
       self.leftHandedHeaderConstraint.priority = (self.isLeftAligned) ? 1 : 999 
       self.rightHandedHeaderConstraint.priority = (self.isLeftAligned) ? 999 : 1 
       self.layoutIfNeeded() 
      }, completion: nil) 

     } else if userHanded == "Left" { 
      UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: { 
       self.leftHandedHeaderConstraint.priority = (self.isLeftAligned) ? 999 : 1 
       self.rightHandedHeaderConstraint.priority = (self.isLeftAligned) ? 1 : 999 
       self.layoutIfNeeded() 
       }, completion: nil) 
     } 
} 
+0

P.S. Примечание для других, чтобы убедиться, что tableView для MultipleSelection так, чтобы не все ячейки одного и того же типа анимировали :) –

Смежные вопросы