2016-08-23 125 views
1

所以我想改變一個布爾值在我的項目中使用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

我沒有得到你的問題。 –

回答

0

好吧!我完全不知道這裏發生了什麼,但我想出瞭如何保持轉換。

而不是創建附件視圖,我直接將目標添加到交換機,並且一切按預期工作。以下是更新後的代碼:

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

試試這個代碼:

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="stackoverflow_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="stackoverflow_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

你看過我的代碼嗎?你怎麼看待這種認識?在我看來更明顯。 –