You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4 iOS实现单选按钮:基于数组构建单选题APP技术求助

Hey there! Let's tackle this single-choice question app together. Using arrays to manage your options is totally doable—here's a step-by-step solution tailored to your code setup:

Implementing Single-Choice Questions with Arrays in iOS

1. First, Define a Clear Question Data Model

Let's create a structured model to hold your question details, including an array for the four options. Add this outside your ViewController class:

struct Question {
    let title: String
    let topic: String
    let options: [String] // This array will store your 4 options
    let correctAnswerIndex: Int // Track which option index is the right answer
}

2. Update Your ViewController Setup

Replace your partial dictionary1 with an array of Question objects, and add a variable to track the user's selected option:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var topicLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    // Array to store all your questions (each has its own options array)
    var questions: [Question] = []
    // Track the currently selected option to enforce single selection
    var selectedIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Configure table view basics
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "OptionCell")
        
        // Load your question data
        loadSampleQuestions()
        // Show the first question when the app starts
        displayQuestion(at: 0)
    }

    // Helper to add sample question data (customize this with your own questions)
    func loadSampleQuestions() {
        let firstQuestion = Question(
            title: "Sample Question",
            topic: "General Knowledge",
            options: ["Option A", "Option B", "Option C", "Option D"],
            correctAnswerIndex: 2
        )
        questions.append(firstQuestion)
        // Add more questions here as needed
    }

    // Helper to update labels with current question details
    func displayQuestion(at index: Int) {
        guard index < questions.count else { return }
        let currentQuestion = questions[index]
        titleLabel.text = currentQuestion.title
        topicLabel.text = currentQuestion.topic
        tableView.reloadData()
    }
}

3. Implement Table View Logic for Options & Single Selection

Add this extension to handle populating the table view with options and managing the single-selection radio button behavior:

extension ViewController {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let currentQuestion = questions.first else { return 0 }
        return currentQuestion.options.count // Returns 4 for your single-choice setup
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath)
        guard let currentQuestion = questions.first else { return cell }

        // Set the option text from the array
        cell.textLabel?.text = currentQuestion.options[indexPath.row]

        // Create a radio button for selection
        let radioButton = UIButton(type: .custom)
        radioButton.setImage(UIImage(systemName: "circle"), for: .normal)
        radioButton.setImage(UIImage(systemName: "circle.fill"), for: .selected)
        radioButton.tag = indexPath.row
        radioButton.addTarget(self, action: #selector(optionTapped(_:)), for: .touchUpInside)

        // Set the button's selected state based on current selection
        radioButton.isSelected = (selectedIndexPath == indexPath)
        cell.accessoryView = radioButton

        return cell
    }

    @objc func optionTapped(_ sender: UIButton) {
        let selectedRow = sender.tag
        let newIndexPath = IndexPath(row: selectedRow, section: 0)

        // Deselect the previous option if one exists
        if let oldIndexPath = selectedIndexPath {
            if let oldCell = tableView.cellForRow(at: oldIndexPath),
               let oldRadioButton = oldCell.accessoryView as? UIButton {
                oldRadioButton.isSelected = false
            }
        }

        // Select the new option
        sender.isSelected = true
        selectedIndexPath = newIndexPath

        // Optional: Check if the selected answer is correct
        guard let currentQuestion = questions.first else { return }
        let isCorrect = (selectedRow == currentQuestion.correctAnswerIndex)
        print("Your answer is \(isCorrect ? "correct!" : "incorrect.")")
    }
}

Key Notes:

  • Array Usage: The options array inside each Question makes it easy to store and iterate over your four choices.
  • Single Selection: The selectedIndexPath variable ensures only one option can be selected at a time—we deselect the old option when a new one is tapped.
  • Cell Reusability: We set the radio button state directly in cellForRowAt to avoid issues with table view cell reuse.

内容的提问来源于stack exchange,提问作者Sudhir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:38:48