uikit2 uikit3
Before SwiftUI existed, apps were built using UIKit. Many associate UIKit with storyboards, but most of the time you just used code to create a UI. By getting rid of the storyboard. In this article, I’ll go into how to create an app in UIKit without a storyboard.
在SwiftUI出现之前,应用是使用UIKit构建的。 许多人将UIKit与情节提要关联起来,但是大多数时候,您只是使用代码来创建UI。 通过摆脱情节提要。 在本文中,我将介绍如何在没有情节提要的情况下在UIKit中创建应用程序。
We are creating a VAT calculator app to calculate the gross price.
我们正在创建一个增值税计算器应用程序以计算总价。
(1. Prepare the app)
First we delete the Main.storyboard and move it to the trash, because we don’t need it!
首先,我们删除Main.storyboard并将其移至垃圾箱,因为我们不需要它!
Second, we empty the area that says Main, so delete the connection and leave it empty.
其次,我们清空Main区域,因此删除连接并将其保留为空。
In the Info.plist we delete the connection Storyboard Name (click on the minus (-) sign). So the complete line will be deltetd. See image.
在Info.plist中,我们删除连接情节提要名称(单击负号(-))。 因此,完整的行将被删除。 见图片。
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let winScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: winScene)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
}
In the SceneDelegate.swift file we change the code as shown above. It is important that you set the name in the rootViewController equal to the name of your ViewController file. If you start the app now you should see a black screen.
在SceneDelegate.swift文件中,我们更改了代码,如上所示。 在rootViewController中将名称设置为等于ViewController文件的名称,这一点很重要。 如果现在启动应用程序,您应该会看到黑屏。
(2. The UI elements)
Now let’s go to the ViewController.swift file and add the following UI element, preferably above the viewDidoad() method.
现在,我们转到ViewController.swift文件,并添加以下UI元素,最好在viewDidoad()方法上方。
private let taxCalculateContentView: UIView = {
let view = UIView()
view.backgroundColor = .blue
view.layer.cornerRadius = 20
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
First we add a UIView in which we subordinate the UI elements. As in all elements, it is important that the translatesAutoresizingMaskIntoContstraints = false. Because that allows us to use our own AutoLayout later.
首先,我们添加一个UIView,在该UIView中我们从属于UI元素。 与所有元素一样, translatesAutoresizingMaskIntoContstraints = false很重要。 因为这样可以让我们稍后使用自己的AutoLayout。
private let titleLabel: UILabel = {
let label = UILabel()
label.text = "Value Added Tax"
label.textAlignment = .center
label.textColor = .systemBlue
label.font = UIFont.boldSystemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let amountTextField: UITextField = {
let textField = UITextField()
textField.backgroundColor = .white
textField.placeholder = "Amount / Net Price"
textField.borderStyle = .roundedRect
textField.keyboardType = .decimalPad
textField.textAlignment = .center
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
private let percentageTextField: UITextField = {
let textField = UITextField()
textField.backgroundColor = .white
textField.placeholder = "Tax in Percent"
textField.borderStyle = .roundedRect
textField.keyboardType = .numberPad
textField.textAlignment = .center
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
private let resultLabel: UILabel = {
let label = UILabel()
label.text = "Gross Price"
label.textAlignment = .center
label.textColor = .systemPink
label.font = UIFont.systemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
Adds two TextFields and two labels below. You can make adjustments yourself or leave my settings.
在下面添加两个TextField和两个标签。 您可以自己进行调整或保留我的设置。
let calculateButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .systemBlue
button.setTitle("Calculate", for: .normal)
button.tintColor = .white
button.layer.cornerRadius = 10
button.clipsToBounds = true
button.addTarget(self, action: #selector(calculateActionButton), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
Finally, we have a button with a link to an action in which we calculate the gross price.
最后,我们有一个带有链接的按钮,该按钮用于计算总价。
(3. SubViews and Auto Layout)
override func viewDidLoad() {
super.viewDidLoad()
taxCalculateContentView.addSubview(titleLabel)
taxCalculateContentView.addSubview(amountTextField)
taxCalculateContentView.addSubview(percentageTextField)
taxCalculateContentView.addSubview(resultLabel)
taxCalculateContentView.addSubview(calculateButton)
view.backgroundColor = .systemBlue
view.addSubview(taxCalculateContentView)
setupAutoLayout()
}
It is important here, that the UI elements are linked to our self-created UIView. They are added in the viewDidLoad () method. Our UIView is then added to the main view. We also have a method for the Auto Layout.
在这里重要的是,UI元素链接到我们自己创建的UIView。 它们被添加到viewDidLoad()方法中。 然后将我们的UIView添加到主视图。 我们也有一种自动布局的方法。
func setupAutoLayout() {
taxCalculateContentView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
taxCalculateContentView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
taxCalculateContentView.heightAnchor.constraint(equalToConstant: view.frame.height / 3).isActive = true
taxCalculateContentView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: taxCalculateContentView.topAnchor, constant: 10).isActive = true
titleLabel.leftAnchor.constraint(equalTo: taxCalculateContentView.leftAnchor, constant: 40).isActive = true
titleLabel.rightAnchor.constraint(equalTo: taxCalculateContentView.rightAnchor, constant: -40).isActive = true
titleLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
amountTextField.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10).isActive = true
amountTextField.leftAnchor.constraint(equalTo: taxCalculateContentView.leftAnchor, constant: 40).isActive = true
amountTextField.rightAnchor.constraint(equalTo: taxCalculateContentView.rightAnchor, constant: -40).isActive = true
amountTextField.heightAnchor.constraint(equalToConstant: 40).isActive = true
percentageTextField.topAnchor.constraint(equalTo: amountTextField.bottomAnchor, constant: 20).isActive = true
percentageTextField.leftAnchor.constraint(equalTo: taxCalculateContentView.leftAnchor, constant: 60).isActive = true
percentageTextField.rightAnchor.constraint(equalTo: taxCalculateContentView.rightAnchor, constant: -60).isActive = true
percentageTextField.heightAnchor.constraint(equalToConstant: 40).isActive = true
resultLabel.topAnchor.constraint(equalTo: percentageTextField.bottomAnchor, constant: 20).isActive = true
resultLabel.leftAnchor.constraint(equalTo: taxCalculateContentView.leftAnchor, constant: 60).isActive = true
resultLabel.rightAnchor.constraint(equalTo: taxCalculateContentView.rightAnchor, constant: -60).isActive = true
resultLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
calculateButton.topAnchor.constraint(equalTo: resultLabel.bottomAnchor, constant: 20).isActive = true
calculateButton.leftAnchor.constraint(equalTo: taxCalculateContentView.leftAnchor, constant: 40).isActive = true
calculateButton.rightAnchor.constraint(equalTo: taxCalculateContentView.rightAnchor, constant: -40).isActive = true
calculateButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
First we create the constraints of our taxCalculateContentView and calculate the height so that it is centered.I will only go into this briefly, as otherwise it would go beyond the length of the article. The other elements are arranged in a way that suits me at first. It is best, to try out the constraints, this is the only way to know what each constraint does.
首先,我们创建taxCalculateContentView的约束并计算高度以使其居中,我将仅对此进行简要介绍,否则它将超出文章的长度。 首先,其他元素的排列方式适合我。 最好尝试一下约束,这是知道每个约束作用的唯一方法。
(4. UIButton Action and Summary)
@objc func calculateActionButton(sender: UIButton!) {
let amount = amountTextField.text?.replacingOccurrences(of: ",", with: ".")
let percentage = percentageTextField.text
if !amount!.isEmpty && !percentage!.isEmpty {
let result = Double(amount!)! * (1 + (Double(percentage!)! / 100))
resultLabel.text = "Gross Price: \(String(format: "%.2f", result))"
}
}
If we now click the button, the calculateActionButton (…) method is called (see above). Here the values of the text fields are transferred, converted into a double and calculated. If the fields are empty, nothing happens. Finally, the result is transferred to the resultLabel.
现在,如果单击按钮,则将调用calculateActionButton(…)方法(请参见上文)。 在此,将传输文本字段的值,将其转换为双精度并进行计算。 如果字段为空,则什么也不会发生。 最后,将结果传输到resultLabel。
This is what the end result should look like. I hope you enjoyed my excursion. UIKit also offers advantages. Despite the time of SwiftUI, you can also work in UIKit without a storyboard and it is advantageous to deal with it. Many tech companies still use UIKit (mostly without a storyboard). So in addition to SwiftUI, you should also know the basics of UIKit, because that can help in the future.
这就是最终结果应该是什么样子。 希望您喜欢我的游览。 UIKit也具有优势。 尽管有SwiftUI的使用时间,您也可以在没有情节提要的情况下在UIKit中工作,并且处理它是有利的。 许多科技公司仍在使用UIKit(大部分没有情节提要)。 因此,除了SwiftUI,您还应该了解UIKit的基础知识,因为这将来会有所帮助。