ios - viewDidLoad 之后如何创建/添加 UIView?

标签 ios swift uiview rx-swift ios-autolayout

我试图在收到网络请求的响应后创建按钮。如何执行此操作并在创建它们之后、加载 View 之后定位它们。我还以编程方式创建 View 并使用自动布局。

CustomView.swift

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

ViewController.swift

// Load custom view
override func loadView() {
    view = CustomView()
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Create buttons after getting response
    viewModel.output.apiOutput
        .subscribe(onNext: { posts in
            for post in posts {
                // create buttons
            }
        })
        .dispose(by: disposeBag)

}

最佳答案

/// Helper function to create a new button.
func createButton(_ title: String) -> UIButton {
    let button = UIButton()
    button.backgroundColor = .blue
    button.setTitle(title, .normal)

    // Add the button as a subview.
    self.view.addSubview(button)
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Just set the viewController's view to your custom view here.
    self.view = CustomView()

    // Create buttons after getting response
    viewModel.output.apiOutput
        .subscribe(onNext: { posts in
            for post in posts {
                // Create a button. Change "title" to the title of your post, etc.
                let button = createButton("Title")
                // Constrain your button here!
            }
        })
        .dispose(by: disposeBag)
}

上面写着 //在此处约束您的按钮! - 如果您想要在行或列中放置多个按钮,我建议使用 UIStackView,并将它们添加为 ArrangedSubviews,例如。

关于ios - viewDidLoad 之后如何创建/添加 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56465693/

相关文章:

ios - Swift Animate 背景不适用于 Collection View 单元格

ios - 禁用 AVSpeechSyntesizer/AVSpeechUtterance 的自动日期检测

swift - CoreML 无法验证输入

ios - 在 viewForHeaderInSection iOS 8 swift 中正确返回 UIView

ios - 不支持 Xcode iOS 8 键盘类型

ios - MPMoviePlayerViewController在iOS 7上不起作用

ios - 在 Swift 中为 Parse 的 PFRelation 声明一个只读的@NSManaged 属性

ios - Swift 在调试和 Release模式下的行为不同

ios - 带有阴影和圆边的 ContainerView

iphone - UIView 如何访问 UIViewController 的属性?