我正在寫我的第一個Swift應用程序的測驗。每個問題都有隨機的方式在屏幕上呈現如下截圖。Swift 3添加刪除子視圖及其內容
我沒有故事板即編程應用程序。編程。我想爲單個視圖控制器內的每個問題創建簡單的分頁流程,而無需使用搭配視圖,表格視圖或導航。
我到目前爲止做了什麼?我有簡單的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)
}
}
這就是我所看到的我點擊繼續。
注:最初想過用搭配或表視圖會像我可以設置爲每個問題水平滾動和使用REST API和地點,每個單元獲取的問題更爲合適。但我只想向用戶展示下一個屏幕,然後點擊繼續。我想用collectionview用戶可以在滑動時移動到下一個屏幕。
Thanks @ Paulw11 - 這將如何幫助從子視圖中刪除標籤?讓我更新我的帖子,以顯示我點擊繼續時看到的內容。 – VK321
在self.view.subviews中查看 { view.removeFromSuperview() } 在添加任何內容之前,先在create_subview()中使用此代碼。 – ChanWarde
發明車輪總是一個不好的做法。這就是爲什麼你應該在故事板內創建VC(或者是一個nib文件,它將是一個VC類型並使用它的視圖),以便爲每個問題提供獨特的用戶界面。 以編程的方式開發用戶界面是一個不好的實踐,你應該在可能的時候開發iOS時避免它。儘可能利用auotlayout。使用故事板/筆尖的可維護性將超級敏捷。 – OhadM