【发布时间】:2025-12-19 22:40:11
【问题描述】:
我在Swift 中找到了有关如何做某事的教程。我在Objective-C 项目的末尾,我尝试将这些类导入Objective-C,但that's been a bug-riddled, time monopolizing disaster,所以我从Swift 转换为Objective-C。
我得到了UIView.h/m 到没有警告/错误的地步,但是在UIViewController 上添加视图是另一回事。我已经在下面发布了我试图“翻译”的初始化代码。我欢迎输入回复:我在搞砸什么。
Swift 类中用于初始化 UIView 的代码:
var parentFrame :CGRect = CGRectZero
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Colors.clear
}
我的“翻译的”Objective-C 类中用于初始化 UIView 的代码
myUIView.h
// At MartinR's suggestion, I removed the pointer here
@property (nonatomic) CGRect parentFrame;
myUIView.m
// No compiler errors -- the errors occur on the UIViewController
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:(self.parentFrame)];
self.parentFrame = CGRectZero;
if (self) {
[super setFrame:self.parentFrame];
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
当我尝试将 UIView 添加到 UIViewController 时出现问题。我无法弄清楚为什么我会收到以下警告:
Swift UIViewController 代码添加 UIView
func addHolderView() {
let boxSize: CGFloat = 75.0
holderView.frame = CGRect(x: view.bounds.width / 2 - boxSize / 2,
y: view.bounds.height / 2 - boxSize / 2,
width: boxSize,
height: boxSize)
holderView.parentFrame = view.frame
holderView.delegate = self
view.addSubview(holderView)
holderView.addOval()
}
我的“翻译的”Objective-C ViewController 充满了实现错误
myUIViewController.h
#import "HolderView.h"
// blah blah
@property (nonatomic, strong) HolderView *holderView;
myUIViewController.m
- (void)addHolderView {
CGFloat boxSize = 75.0;
// WARNING: The following line says "expression result unused"
[self.holderView initWithFrame:CGRectMake(_view.bounds.size.width / 2 - boxSize / 2,
_view.bounds.size.height / 2 - boxSize / 2,
boxSize,
boxSize)];
// Warning here went away by removing the pointer on CGRect parentFrame
self.holderView.parentFrame = view.frame;
self.holderView.delegate = self; // I have the delegate stuff squared away
[self.view addSubview:self.holderView];
}
感谢您的阅读。
已更新以反映 MartinR 在 cmets 中的输入。
我更新了上面的代码以删除CGRect parentFrame 上的指针。
【问题讨论】:
-
一旦您意识到
parentFrame不应该不是指针,您就可以大幅清理您的代码:) -
谢谢@MartinR!我正在我的 Interface Builder “舒适区”之外冒险。我在这件事上花费的时间比我愿意承认的要多。如果你还有更多要补充的,我会全力以赴。
-
@property (nonatomic) CGRect parentFrame;没有*。 (你知道指针是什么吗?)。然后清理你的initWithFrame方法。
标签: objective-c swift uiview uiviewcontroller translate