UIswitch在单独的视图控制器中激活或停用图像阵列

时间:2017-07-27 23:02:02

标签: ios swift xcode uisplitviewcontroller uiswitch

概述 - 我正在制作一个flashcard应用程序。我已经达到了用户可以左右滑动图像阵列的程度。图像被分成11个不同的组,所有组加起来一个最终阵列,用户可以轻扫(下面的代码)。

import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

@IBAction func home(_ sender: Any) {
    performSegue(withIdentifier: "home", sender: self)
}

@IBOutlet weak var imgPhoto: UIImageView!

struct List {
    let words: [String]
    var active: Bool
}

let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)

let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)

let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)

let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)

let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)

let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)

let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)

let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)

let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)

let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)

let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)

var imageIndex: Int = 0

var imageList: [String] {

    let wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]



    let active = wordLists.reduce([]) { (result:[String], list:List) in
        if list.active {
            return result + list.words

        } else {
            return result
        }
    }

    return active

}




override func viewDidLoad() {
    super.viewDidLoad()

    imgPhoto.image = UIImage(named: imageList[imageIndex])

    // Do any additional setup after loading the view.
    imgPhoto.isUserInteractionEnabled = true

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    leftSwipe.cancelsTouchesInView = false

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    rightSwipe.cancelsTouchesInView = false

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

}

func Swiped(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.right :
            print("User swiped right")

            // decrease index first

            imageIndex -= 1

            // check if index is in range

            if imageIndex < 0 {

                imageIndex = imageList.count - 1

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        case UISwipeGestureRecognizerDirection.left:
            print("User swiped Left")

            // increase index first

            imageIndex += 1

            // check if index is in range

            if imageIndex > imageList.count - 1 {

                imageIndex = 0

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        default:
            break //stops the code/codes nothing.
        }
    }
}
}

现在 - 我正在设置页面(下图)。上面代码中的11个单词列表中的每一个都有1个开关。最顶层的开关将控制list1,第二个开关将控制list2等...

enter image description here

问题 - 是我想为每个交换机添加功能。当开关处于关闭位置时,与其关联的图像组不应包括在最终阵列中,并且当用户轻扫闪卡时不会显示。到目前为止,我的设置页面的代码如下。我尝试过尝试不同的代码,例如将开关连接到ViewController并添加Override func,但我不知道在这一点上去哪里。

import UIKit

protocol WordSelectionDelegate: class {
func wordSelected(newWord: Word)
}

class MasterViewController: UITableViewController {
var words = [Word]()

weak var delegate: WordSelectionDelegate?

override func prepare(for segue: UIStoryboardSegue, sender: SecondViewController) {
    if let vc = segue.destination as? MasterViewController {
        vc.wordLists = wordLists
    }
}


@IBAction func switchAction(_ sender: UISwitch) {
     wordList[sender.tag].active = rollIntoLoanSwitch.isOn
}



override func viewDidLoad() {
    super.viewDidLoad()



}
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

    self.words.append(Word(name: "initial /l/ 1 syllable", description: "lake lamb lamp lark leaf leash left leg lime lion lips list lock log look love lunch"))

    self.words.append(Word(name: "initial /l/ multisyllabic", description: ""))

    self.words.append(Word(name: "intersyllabic /l/", description: ""))

    self.words.append(Word(name: "final /l/", description: ""))

    self.words.append(Word(name: "initial /pl/", description: ""))

    self.words.append(Word(name: "initial /bl/", description: ""))

    self.words.append(Word(name: "initial /fl/", description: ""))

    self.words.append(Word(name: "initial /gl/", description: ""))

    self.words.append(Word(name: "initial /kl/", description: ""))

    self.words.append(Word(name: "initial /sl/", description: ""))

    self.words.append(Word(name: "final /l/ clusters", description: ""))


}


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

// MARK: - Table view data source

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return self.words.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    // Configure the cell...
    let word = self.words[indexPath.row]
    cell.textLabel?.text = word.name
    return cell
}

override  func tableView(_ tableView: UITableView, didSelectRowAt
    indexPath: IndexPath) {
    let selectedMonster = self.words[indexPath.row]
    self.delegate?.wordSelected(newWord: selectedMonster)
    if let Detail = self.delegate as? Detail {
        splitViewController?.showDetailViewController(Detail, sender: nil)
    }

}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, can

如何解决这个问题的任何想法将不胜感激。谢谢

enter image description here

1 个答案:

答案 0 :(得分:0)

您缺少程序的许多部分来完成这项工作。他们是:

  1. 设置UISwitch控件的目标方法。
  2. 设置UISwitch控件的标记号。
  3. SecondViewController
  4. 中刷新显示的图像

    要设置UISwitch控件的目标方法,您需要在每个开关上调用addTarget(_:action:for:),并将引用传递给您拥有的MasterViewController。如果您这样做,那么我建议您在Interface Builder中为UISwitch控件设置标记。例如,假设您的UISwitch标记为1:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    
        // Configure the cell...
        let word = self.words[indexPath.row]
        cell.textLabel?.text = word.name
        if let switchControl = cell.viewWithTag(1) as UISwitch {
            switchControl.addTarget(self, action: #selector(switchAction(_:)), for: .valueChanged)
        }
    
        return cell
    }
    

    对于第3点,MasterViewController中的数据与SecondViewController中的数据不同。您需要获取对SecondViewController的引用,然后更新其中的数据,并告诉它重新显示所选图像。有关如何从拆分视图控制器访问对等视图控制器,请参阅this question for details