我正在尝试以编程方式创建一个 Stackview,其中包含一个显示“Hello world”的 TextField
class stackview: UIViewController {
func setupview() {
// Define TextField
let Textfield = UITextView()
Textfield.allowsEditingTextAttributes = false
Textfield.translatesAutoresizingMaskIntoConstraints = false
Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
Textfield.isEditable = false
// Define the stackview, and setting up the attributes
let stackview = UIStackView()
stackview.axis = UILayoutConstraintAxis.horizontal
stackview.distribution = UIStackViewDistribution.equalCentering
stackview.alignment = UIStackViewAlignment.center
stackview.spacing = 5
stackview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackview)
stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Textfield.text = "hello"
view.addSubview(Textfield)
}
在我的 Viewcontroller.swift 中,我想在 ViewDidLoad 中访问这个函数
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var level = stackview()
level.setupview()
}
但是 Hello world 似乎没有出现!
最佳答案
做这样的事情。
stackview.swift
import UIKit
class stackview: UIViewController {
func setupview(myView: UIView) {
// Define TextField
let Textfield = UITextView()
Textfield.allowsEditingTextAttributes = false
Textfield.translatesAutoresizingMaskIntoConstraints = false
Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
Textfield.isEditable = false
// Define the stackview, and setting up the attributes
let stackview = UIStackView()
stackview.axis = UILayoutConstraintAxis.horizontal
stackview.distribution = UIStackViewDistribution.equalCentering
stackview.alignment = UIStackViewAlignment.center
stackview.spacing = 5
stackview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackview)
stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Textfield.text = "hello"
myView.addSubview(Textfield)
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let level = stackview()
level.setupview(myView: self.view)
}
}
关于ios - 我如何使用多个文件在 viewController 中访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44918797/