UIViewController继承:将参数传递给作为UIViewController子类的父类

时间:2019-05-15 16:31:20

标签: ios swift

我正在创建一个应用程序以对用户进行解剖测验。我创建了一个QuizControl类,它是UIViewController的子类,它使用“问题”结构来概述我的需求。它创建一个看起来像这样的通用模板 picture。这是一个通用的大纲,带有一个问题标签,下面带有4个按钮,分别与不同的答案选项相对应。

我的问题是,如果可能的话,我想保持这个QuizControl类的通用性,并让其他类继承它,同时仅将其问题数组传递回QuizControl类。我不明白如何将参数传递回类viewDidLoad()构造函数。

这是我的QuizControl class,它是UIViewControl的子类。 这是孩子:TorsoQuiz


如果看不到图片,则代码如下所示:

QuizControl

struct Question {
    var Question : String!
    var Answers : [String]!
    var Answer : Int!
}

class QuizControl: UIViewController {

@IBOutlet var Buttons: [UIButton]!
@IBOutlet var QLabel: UILabel!

var Questions = [Question]()
var QNumber = Int()
var AnswerNumber = Int()
var correct = Int()
var incorrect = Int()
override func viewDidLoad() {
    super.viewDidLoad()
    correct = 0
    incorrect = 0
    Questions = [Question(Question: "Question 1", Answers: ["Answer 0","Answer 1","Answer 2","Answer 3"], Answer: 2),
                 Question(Question: "Question 2", Answers: ["Answer 4","Answer 5","Answer 6","Answer 7"], Answer: 0),
                 Question(Question: "Question 3", Answers: ["Answer 8","Answer 9","Answer 10","Answer 11"], Answer: 1),
                 Question(Question: "Question 4", Answers: ["Answer 12","Answer 13","Answer 14","Answer 15"], Answer: 2),
                 Question(Question: "Question 5", Answers: ["Answer 16","Answer 17","Answer 18","Answer 19"], Answer: 3),]
    pickQuestion()
}

TorsoQuiz

class TorsoQuiz: QuizControl {

var torsoQuestions = [Question(Question: "My chest hurts and I'm having difficulty breathing", Answers: ["Check for Asthma","Check family history of heart problems","Call an ambulance","Sample diagnosis 3"], Answer: 2),
Question(Question: "Question 2", Answers: ["Answer 4","Answer 5","Answer 6","Answer 7"], Answer: 0),
Question(Question: "Question 3", Answers: ["Answer 8","Answer 9","Answer 10","Answer 11"], Answer: 1),
Question(Question: "Question 4", Answers: ["Answer 12","Answer 13","Answer 14","Answer 15"], Answer: 2),
Question(Question: "Question 5", Answers: ["Answer 16","Answer 17","Answer 18","Answer 19"], Answer: 3),]
//Pass these questions/answers to Quiz Control?

override func viewDidLoad() {
    super.viewDidLoad()

如何将参数传递回QuizControl? 我已经看到的答案已经使用.init()和.init()了吗?但是由于答案很旧,解决方案无法在Xcode 10.2.1和Swift 5上使用。解决方案使用frame:参数,编译器不会接受。感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

我不想粗鲁或批评您的问题,但是看起来您需要在构建这样的不太简单的应用程序之前提高对计算机编程的一般理解。 我的观点是,您缺少面向对象编程和Cocoa Touch / Swift中的一些关键概念。 我推荐这门课程来引导您的编程生涯。 hackingwithswift.com

编码愉快!

答案 1 :(得分:0)

如果我正确理解了您的问题,则似乎是继承问题。我脑海中浮现出两种解决方案。

我想说,最简单的解决方案是利用继承的Questions属性。 (顺便说一句,迅速的属性/变量应该为lowerCamelCased。)因此,在TorsoQuiz控制器中,在调用super.viewDidLoad()之前,只需将Questions赋给torsoQuestions

但是,另一种合适的解决方案是使用依赖项注入来插入一个基于身体区域管理问题的类。您可以使用方法QuestionManager设置一个协议,例如getQuestion,然后在加载视图控制器之前将其实现注入到类中。它可以满足您的需求,但可以使扩展(和测试)变得更加容易。

这里有一个tutorial关于依赖项注入的信息,我还没看过,但是看起来还不错。

祝你好运,如果不清楚,请再提出其他问题。