VK3*_*321 3 iphone uitableview uiview ios swift
我正在编写我的第一个Swift应用程序进行测验.每个问题都有随机的方式在屏幕上呈现如下截图.
我是没有故事板的编程应用程序即.编程.我想在单个viewcontroller中为每个问题创建简单的分页流,而不使用Collocationview,Tableview或navigation.
到目前为止我做了什么?我有简单的viewcontroller与UIView()添加为子视图.我正在动态添加问题组件.现在,一旦用户点击继续,我想删除子视图并添加新的子视图和新问题.我能够删除子视图但子视图上的内容似乎仍然存在,因为我可以看到它被覆盖.
要获得更多说明,请查看我的代码.
import UIKit
class QuizController: UIViewController {
let subView = UIView()
var currentQuestion:Int = 1;
let questions = ["This is question 1", "Hello to question 2", "Question 3"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
setup_layout()
}
func setup_layout(){
let closeBtn = UIButton(frame: CGRect(x: 5, y: 10, width: 200, height: 50))
closeBtn.backgroundColor = UIColor.red
closeBtn.setTitle("Close", for: .normal)
closeBtn.addTarget(self, action: #selector(close), for: .touchUpInside)
view.addSubview(closeBtn)
//dynamic view
create_subview()
}
func nextQuestion(){
print("Show next")
if let viewWithTag = self.view.viewWithTag(currentQuestion) {
viewWithTag.removeFromSuperview()
currentQuestion += 1;
create_subview()
} else {
print("No!")
}
}
func create_subview(){
let heightOfView = view.frame.size.height
let widthOfView = view.frame.size.width
subView.tag = currentQuestion
subView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2)
subView.frame = CGRect(x: 0, y: 60, width: self.view.frame.width, height: heightOfView - 60)
self.view.addSubview(subView)
let txtLabel1 = UILabel(frame: CGRect(x: 35, y: 120, width: widthOfView , height: 20))
txtLabel1.text = questions[currentQuestion-1]
txtLabel1.font = txtLabel1.font.withSize(12)
subView.addSubview(txtLabel1)
let nextBtn = UIButton(frame: CGRect(x: 5, y: 300, width: 200, height: 50))
nextBtn.backgroundColor = UIColor.red
nextBtn.setTitle("Continue", for: .normal)
nextBtn.addTarget(self, action: #selector(nextQuestion), for: .touchUpInside)
subView.addSubview(nextBtn)
}
func close(){
self.dismiss(animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我看到的点击继续.
注意:最初考虑使用Collocation或Table视图会更合适,因为我可以设置为每个问题水平滚动并使用REST API获取问题并放置到每个单元格.但我想只向用户显示一次下一个屏幕然后点击继续.我想使用collectionview用户可以在滑动时移动到下一个屏幕.
刚刚找到答案.我假设删除子视图也会自动删除子视图中的所有组件,即.在我的情况下UILable和UIButton.
我必须单独删除它们.
for subview in self.subView.subviews {
subview.removeFromSuperview()
}
Run Code Online (Sandbox Code Playgroud)
现在我可以添加标签到组件并删除如下:
for subview in self.subView.subviews {
if (subview.tag == 1) {
subview.removeFromSuperview()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7355 次 |
最近记录: |