【发布时间】:2014-06-10 01:47:56
【问题描述】:
tl;dr:我如何告诉 Swift 我正在用 UIView 的子类覆盖 MyViewController 的 view 属性?
我想做的事
我非常喜欢为UIViewController 的视图提供UIView 的子类。例如:
// MyView --------------------------------------------------------
@interface MyView: UIView
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation MyView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_tableView = [[UITableView alloc] initWithFrame:frame];
}
return self;
}
@end
// MyViewController ----------------------------------------------
@interface MyViewController: UIViewController <UITableViewDataSource>
@property (nonatomic, retain) MyView *view;
@end
@implementation MyViewController
- (void)loadView {
self.view = [[MyView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.tableView.dataSource = self;
// etc.
}
@end
这很棒,因为它将视图创建和布局逻辑与视图控制器分开。好的,好的。
据我所知,这翻译成 Swift 是这样的:
// MyView --------------------------------------------------------
class MyView: UIView {
let tableView: UITableView!
init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView(frame: frame)
}
}
// MyViewController ----------------------------------------------
class MyViewController: UIViewController, UITableViewDataSource {
override func loadView() {
view = MyView(frame: UIScreen.mainScreen().bounds)
}
override func viewDidLoad() {
super.viewDidLoad()
// this causes the compiler to complain with:
// 'UIView' does not have a member named 'tableView'
self.view.tableView.dataSource = self
}
}
问题是我似乎不知道如何告诉视图控制器它的view 是MyView 的一个实例而不是UIView 本身。
尝试失败
这是我迄今为止尝试过的:
我在MyViewController 的顶部试过这个,但出现以下错误:
override var view: MyView!
// error: Cannot override mutable property 'view' of
// type 'UIView' with covariant type 'MyView!'
我在loadView 中尝试过这个,但没有运气:
view = MyView(frame: UIScreen.mainScreen().bounds) as MyView
// this produces the same error as in the original code:
// 'UIView' does not have a member named 'tableView'
那么问题来了
如何告诉 Swift 我正在使用子类 MyView 之一覆盖 MyViewController 的 view 属性?这甚至可能吗?如果没有,为什么不呢?
【问题讨论】:
标签: ios uiview uiviewcontroller swift