UISwitch约束和动画中断tableview.reloadData()

问题描述:

所以我想改变一个布尔值在我的项目中使用UISwitch。交换机位于我的单元格右侧,并通过Interface Builder添加了约束条件。UISwitch约束和动画中断tableview.reloadData()

我已经装配了开关来调用switchChanged方法,该方法设置了bool值,然后重新加载tableView以反映更改后的值。

开关正常工作,设置切换时的布尔值。但是,当switchChanged方法调用self.tableView.reloadData()时,交换机重新定位在单元格的左上角,并且它不再动画,尽管它仍然正常工作。有些东西正在破坏开关,但作为新手iOS开发人员,我不确定如何开始故障排除。

下面是相关代码:

cellSwitch.addTarget(self, action: #selector(self.switchChanged), 
    forControlEvents: UIControlEvents.TouchUpInside) 

然后:

func switchChanged(sender: UISwitch) -> Void { 
    print("Switch changed to \(sender.on).") 

    if sender.on { 
     self.acknowledged = "confirmed" 
    } else { 
     self.acknowledged = "conflicted" 
    } 
    tableView.reloadData() 
} 

不知何故,tableView.reloadData()线打破了开关。除开关位置和动画以外的其他一切工作。任何帮助表示赞赏!

编辑:

switchChanged()该方法是在我的视图控制器实现。

这里是上面提到的约束:

These

+1

你需要证明你已经添加的约束。另外,switchChanged()方法在哪里实现?在单元格或视图控制器中? – Abizern

+0

'switchChanged()'发生在视图控制器 – SpacemanDeMars

+0

我没有得到你的问题。 –

好吧!我完全不知道这里发生了什么,但我想出了如何保持转换。

而不是创建附件视图,我直接将目标添加到交换机,并且一切按预期工作。以下是更新后的代码:

customCell.acknowledgedSwitch.addTarget(self, 
    action: #selector(self.switchChanged), 
    forControlEvents: UIControlEvents.TouchUpInside) 

试试这个代码:

ViewController.swift

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CellWithSwitchDelegate { 

@IBOutlet var tableView: UITableView! 
var switchOn = true 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    tableView.delegate = self 
    tableView.dataSource = self 
} 

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if let cell = tableView.dequeueReusableCellWithIdentifier("CellWithSwitch") as? CellWithSwitch { 
     cell.delegate = self 
     cell.switcher.on = switchOn 
     return cell 
    } 

    return UITableViewCell() 
} 

func switchValueChanged(cell: CellWithSwitch, sender: UISwitch) { 
    print("Switch changed to \(sender.on).") 
    switchOn = sender.on 

    let indexSet = NSIndexSet(index: 0) 
    tableView.reloadSections(indexSet, withRowAnimation: .Left) 
} 
} 

CellWithSwitch.swift

import UIKit 

protocol CellWithSwitchDelegate { 
func switchValueChanged(cell: CellWithSwitch, sender: UISwitch) 
} 

class CellWithSwitch: UITableViewCell { 

var delegate: CellWithSwitchDelegate? 
@IBOutlet var switcher: UISwitch! 

@IBAction func valueChanged(sender: UISwitch) { 

    if let delegate = self.delegate { 
     delegate.switchValueChanged(self, sender: sender) 
    } 
} 
} 

Main.storyboard

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r"> 
<dependencies> 
    <deployment identifier="iOS"/> 
    <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/> 
    <capability name="Constraints to layout margins" minToolsVersion="6.0"/> 
</dependencies> 
<scenes> 
    <!--View Controller--> 
    <scene sceneID="tne-QT-ifu"> 
     <objects> 
      <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="*_39104992" customModuleProvider="target" sceneMemberID="viewController"> 
       <layoutGuides> 
        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> 
        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> 
       </layoutGuides> 
       <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> 
        <rect key="frame" x="0.0" y="0.0" width="600" height="600"/> 
        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> 
        <subviews> 
         <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="kbL-PU-bnt"> 
          <rect key="frame" x="0.0" y="28" width="600" height="572"/> 
          <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> 
          <prototypes> 
           <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="CellWithSwitch" id="Xxo-pE-rjH" customClass="CellWithSwitch" customModule="*_39104992" customModuleProvider="target"> 
            <rect key="frame" x="0.0" y="28" width="600" height="44"/> 
            <autoresizingMask key="autoresizingMask"/> 
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="Xxo-pE-rjH" id="bAF-fu-1lQ"> 
             <rect key="frame" x="0.0" y="0.0" width="600" height="43"/> 
             <autoresizingMask key="autoresizingMask"/> 
             <subviews> 
              <switch opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" contentHorizontalAlignment="center" contentVerticalAlignment="center" on="YES" translatesAutoresizingMaskIntoConstraints="NO" id="gWn-Oz-kuT"> 
               <rect key="frame" x="543" y="6" width="51" height="31"/> 
               <connections> 
                <action selector="valueChanged:" destination="Xxo-pE-rjH" eventType="valueChanged" id="clu-XE-TxT"/> 
               </connections> 
              </switch> 
             </subviews> 
             <constraints> 
              <constraint firstItem="gWn-Oz-kuT" firstAttribute="centerY" secondItem="bAF-fu-1lQ" secondAttribute="centerY" id="DhQ-ae-Twa"/> 
              <constraint firstItem="gWn-Oz-kuT" firstAttribute="trailing" secondItem="bAF-fu-1lQ" secondAttribute="trailingMargin" id="aCN-km-CK1"/> 
             </constraints> 
            </tableViewCellContentView> 
            <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/> 
            <connections> 
             <outlet property="switcher" destination="gWn-Oz-kuT" id="kG6-g5-aiA"/> 
            </connections> 
           </tableViewCell> 
          </prototypes> 
         </tableView> 
        </subviews> 
        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/> 
        <constraints> 
         <constraint firstItem="kbL-PU-bnt" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="3Df-X8-7Qt"/> 
         <constraint firstItem="kbL-PU-bnt" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="Tqy-17-xK7"/> 
         <constraint firstAttribute="trailing" secondItem="kbL-PU-bnt" secondAttribute="trailing" id="iFb-Yl-HBW"/> 
         <constraint firstItem="kbL-PU-bnt" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="isL-f5-3bE"/> 
        </constraints> 
       </view> 
       <connections> 
        <outlet property="tableView" destination="kbL-PU-bnt" id="9kH-Gx-tmj"/> 
       </connections> 
      </viewController> 
      <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> 
     </objects> 
     <point key="canvasLocation" x="753" y="576"/> 
    </scene> 
</scenes> 
</document> 
+0

你看过我的代码吗?你怎么看待这种认识?在我看来更明显。 –