首页 > 解决方案 > 如何在 Objective-C 控制器中以编程方式加载用 swift 编写的自定义 XIB 视图

问题描述

我为 UIView 创建了一个名为 popUpView.xib 的 XIB 和一个与之关联的 swift 文件 popUpView.swift

我的 popUpView.swift 代码是这样的:

@objc class popUpView: UIView {

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var mobileNumberTF: UITextField!
    @IBOutlet weak var customerIdTF: UITextField!
    @IBOutlet weak var panNumberTF: UITextField!
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var saveBtn: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initSubViews()
    }        
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.initSubViews()
    }
    
    func initSubViews() {
        
        let name = String(describing: type(of: self))
        let nib = UINib(nibName: name, bundle: .main)
        nib.instantiate(withOwner: self, options: nil)
        
        self.addSubview(self.containerView)
        self.containerView.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraints()
    }
    
    func addConstraints() {
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: containerView.topAnchor),
            self.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
        ])
    }
}

现在我正在尝试将此视图作为弹出窗口加载到用 Objective-C 编写的 ViewController 中

在我的 ViewController 中,我是这样调用的:

-(void)showPopUpView {
    
         popUpView *popUpView = [[popUpView alloc] initWithFrame:CGRectZero];
        [self.view addSubview:popUpView];
        [popUpView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:25].active = YES;
        [popUpView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:25].active = YES;
        [popUpView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:25].active = YES;
        [popUpView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:25].active = YES;    
}

在 viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showPopUpView];
}

I think I might be doing it the wrong way. What is the right way to load this custom view programatically in Obj-C?

标签: iosobjective-cswiftxcode

解决方案


自从我上次这样做以来我就很好奇,所以我创建了一个项目来测试它。这就是它对我的工作方式。

我的xib: 在此处输入图像描述

我的弹出视图.m 在此处输入图像描述

我的 ViewController.m 在此处输入图像描述

将代码添加到此 GitHub 存储库: https ://github.com/ArunEA/ObjcViewWithNib


推荐阅读