ios - 如何在 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?
解决方案
自从我上次这样做以来我就很好奇,所以我创建了一个项目来测试它。这就是它对我的工作方式。
将代码添加到此 GitHub 存储库: https ://github.com/ArunEA/ObjcViewWithNib
推荐阅读
- html - Angular Material 表选择行但需要更多数据
- oracle - trimspool ON 在假脱机时从最后一列中删除空间
- java - 使用 DexClassLoader 时如何获取 Activity 中字段的当前值?
- node.js - Webpack resolve.alias 在节点/服务器端不起作用
- admob - 横幅测试广告完美显示,但真实广告未显示 android 应用
- laravel - Laravel 7 - 需要做什么才能将站点置于生产模式?
- r - R中的包'titletoc'
- r - 用两个分组变量绘制直方图
- android - 一遍又一遍地购买相同的物品而不消费 - In App purchase android
- wso2 - 如何连接到外部 PRIMARY LDAP 服务器 WSO2IS 5.10.0