ios - 如何添加 xib View 以查看 Controller swift 3

标签 ios swift xib

我正在尝试将此 XIB View 添加到我的 View Controller 中:

import UIKit

class TranslateView: UIView {
    @IBOutlet var TranslateView: UIView!

    override init(frame: CGRect){
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit(){
        Bundle.main.loadNibNamed("TranslateView", owner: self, options: nil)
        addSubview(TranslateView)
        TranslateView.frame = self.bounds
        TranslateView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

我在这里将它加载到我的 View Controller 中:

import UIKit
import AVFoundation
import Vision

class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
    let captureSession = AVCaptureSession()

    let button: UIButton = {
        let button = UIButton()

        button.addTarget(self, action: #selector(ViewController.pressed(sender:)),for: .touchUpInside)
        button.backgroundColor = UIColor.clear
        button.setTitle("Translate", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCaptureSession()
        view.addSubview(button)
    }

    @objc func pressed(sender: UIButton!) {
        //add label
        button.removeFromSuperview()

        let headerView = Bundle.main.loadNibNamed("TranslateView", owner:
            self, options: nil)?.first as? TranslateView
        self.view.addSubview(headerView!)
        headerView?.frame = CGRect(x:0, y: 0, width: view.frame.width, height: 50.0)
    }

我删除了大部分代码以使这个问题简短。我没有使用 Storyboard,因为我想使用实时摄像头 View 作为我的应用程序的背景。而且这样做是最简单的。我想要发生的是,当我按下按钮时,整个屏幕应该被替换为一个新 View ,即 TranslateView.xib 。

希望有人能帮忙。或者,如果有更好更简单的方法然后使用 XIB 获得相同的结果,请告诉我。

请给出 Swift 3 中的代码示例,而不仅仅是解释该做什么,因为我已经知道我需要做什么,只是不知道如何编码。

最佳答案

尝试修改这段代码

let headerView = Bundle.main.loadNibNamed("TranslateView", owner:
    self, options: nil)?.first as? TranslateView

为此

let headerView = TranslateView()

关于ios - 如何添加 xib View 以查看 Controller swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48122732/

相关文章:

swift - 在 SKScene 中隐藏和取消隐藏按钮

ios - 在StoryTable之外的UITableViewController Xib中,静态单元格选项不可用

ios - UIAlertView 不在屏幕中央

ios - 当我的 UIViewController 在我的 Swift 应用程序中显示给用户时,如何检查它是否被查看?

ios - Worklight Cordova 应用程序 SplashScreen 在应用程序启动期间旋转

ios - 如何使 UICollectionView 宽度依赖于屏幕尺寸?

ios - 如何检查解析 Xcode 中获取的用户名

iphone - 将 XIB 加载到 UIView

ios - 将字符串值传递给 viewcontroller 但得到 EXC_BAD_ACCESS

ios - AVCam 保存全屏捕获的图像