我找到了一个教程,它完全符合我现有的Objective-C项目中的要求,但它是用Swift编写的。我理解斯威夫特的一切,但我有一个噩梦般的时间"翻译" Objective-C的UIView's
初始化程序。这应该很简单,但我无法弄清楚。
我的代码没有崩溃,但它并没有加载任何东西。我在UIViewController
中设置了一个断点,以便在我尝试加载UIView
子类时看到发生了什么,以及我在看到的内容:
(lldb) po self.boxSize
75
(lldb) po self.holderView.frame
(origin = (x = 0, y = 0), size = (width = 0, height = 0))
(origin = (x = 0, y = 0), size = (width = 0, height = 0))
(lldb) po self.holderView
nil
以下是我试图"复制"在Objective-C中。
HolderView.swift:
class HolderView: UIView {
var parentFrame :CGRect = CGRectZero
weak var delegate:HolderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Colors.clear
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
// A bunch of class methods
}
这是我的"翻译" Objective-C .h / .m文件:
HolderView.h:
#import <UIKit/UIKit.h>
@protocol HolderViewDelegate <NSObject>
// delegate methods
@ end
@interface HolderView : UIView
@property (nonatomic, weak) id <HolderViewDelegate> delegate;
@property (nonatomic) CGRect frame;
@property (nonatomic) CGRect parentFrame;
HolderView.m:
- (instancetype)initWithFrame:(CGRect)frame
{
self.parentFrame = CGRectZero;
self = [super initWithFrame:frame];
if (self) {
[super setFrame:self.parentFrame];
self.backgroundColor = [UIColor orangeColor]; // Added to see if it's working
NSLog(@"anyone home?");
}
return self;
}
这是Swift&amp; amp;的代码。 Objective-C UIViewControllers
添加UIView
:
ViewController.swift
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()
}
这是我的&#34;翻译&#34; Objective-C View Controller:
- (void)addHolderView {
self.boxSize = 75.0; // I added as a global variable, as local returned NULL when I tried locally
self.holderView.frame = CGRectMake(self.view.bounds.size.height / 2 - self.boxSize / 2,
self.view.bounds.size.width / 2 - self.boxSize / 2,
self.boxSize,
self.boxSize);
self.holderView.parentFrame = self.view.frame;
self.holderView = [self.holderView initWithFrame:self.holderView.frame];
self.holderView.delegate = self;
NSLog(@"addHolderView called");
[self.view addSubview:self.holderView];
}
感谢您的阅读。
答案 0 :(得分:1)
这段代码怎么样..
- (void)addHolderView {
self.boxSize = 75.0; // I added as a global variable, as local returned NULL when I tried locally
CGRect frame = CGRectMake(self.view.bounds.size.height / 2 - self.boxSize / 2,
self.view.bounds.size.width / 2 - self.boxSize / 2,
self.boxSize,
self.boxSize);
self.holderView = [[HolderView alloc] initWithFrame: frame];
self.holderView.parentFrame = self.view.frame;
self.holderView.delegate = self;
NSLog(@"addHolderView called");
[self.view addSubview:self.holderView];
}