2016-08-23 3 views
1

Also versuche ich einen Bool-Wert mit einem UISwitch in meinem Projekt zu ändern. Der Schalter befindet sich auf der rechten Seite meiner Zelle und wird durch Einschränkungen, die über den Interface Builder hinzugefügt wurden, gehalten.UISwitch Constraints und Animation Pause auf Tableview.ReloadData()

Ich habe den Schalter geriggt, um eine switchChanged Methode aufzurufen, die den Bool-Wert einstellt, und lädt dann die TableView neu, um den geänderten Wert widerzuspiegeln.

Der Switch funktioniert ordnungsgemäß und legt den Bool-Wert beim Umschalten fest. Wenn die switchChanged Methode jedoch self.tableView.reloadData() aufruft, wird der Schalter oben links in der Zelle neu positioniert und animiert nicht mehr, obwohl es weiterhin ordnungsgemäß funktioniert. Irgendetwas bricht den Schalter, aber als unerfahrener iOS-Entwickler bin ich mir nicht sicher, wie ich mit der Fehlersuche beginnen soll. Hier

ist der entsprechende Code:

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

Und dann:

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

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

Irgendwie ist der tableView.reloadData() Linie den Schalter bricht. Alles andere funktioniert außer der Schalterposition und Animation. Jede Hilfe wird geschätzt!

Edit:

Die switchChanged() Methode wird in meiner Ansicht-Controller implementiert.

Hier sind die Einschränkungen oben erwähnt:

These

+1

Sie müssen die Einschränkungen zeigen, dass Sie hinzugefügt haben. Wo wird auch die 'switchChanged()' Methode implementiert? In der Zelle oder der View-Controller? – Abizern

+0

'switchChanged()' passiert in der View-Controller – SpacemanDeMars

+0

Ich bekomme Ihre Frage nicht. –

Antwort

0

Stimmt! Ich habe absolut keine Ahnung, was hier passiert, aber ich habe herausgefunden, wie ich den Schalter an Ort und Stelle halten kann.

Anstatt die Zubehöransicht zu erstellen, füge ich das Ziel direkt zum Switch hinzu, und alles funktioniert wie erwartet. Hier ist der aktualisierte Code:

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

Versuchen Sie diesen Code:

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

Haben Sie sich meinen Code angeschaut? Was denkst du über eine solche Erkenntnis? Es scheint mir offensichtlicher. –