我試圖通過將一個簡單的 Swift 應用程式轉換為它來了解 NSLayoutAnchor 在 Objective-C 中的作業原理。Swift 應用程式創建了一個 NSView 子類,它將其圖層的背景顏色設定為隨機生成的顏色(帶有 NSColor 的擴展),然后在 AppDelegate(內部application:didFinishLaunchingWithOptions)中創建它的兩個實體,然后創建約束陣列,將兩個視圖添加到超級視圖,激活約束并且......就是這樣。
在我嘗試轉換所有內容的 Objective-C 版本中,似乎兩個自定義 NSView 子類實體從未被初始化。一步一步的除錯顯示它們的值為 = nil,當應用程式啟動時,控制臺顯示:
-[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]
由此我推斷出我初始化我的 NSView 子類的方式可能有問題,但即使用鴨子解釋我也找不到可能有問題的地方。這是 ColorView.m 中的代碼(“RandomColor.h”)是獲取randomColor方法的擴展:
#import "ColorView.h"
#import "RandomColor.h"
@implementation ColorView
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (self) {
self.wantsLayer = YES;
self.layer = [[CALayer alloc] init];
self.layer.backgroundColor = [[[NSColor alloc] randomColor] CGColor];
}
NSLog(@"Color View Initialized");
return self;
}
@end
這是擴展程式,如果您想對其進行測驗,但這似乎不是問題:
@implementation NSColor (RandomColor)
- (NSColor *)randomColor {
CGFloat r = drand48();
CGFloat g = drand48();
CGFloat b = drand48();
CGFloat alpha = 1.0;
return [NSColor colorWithRed:r green:g blue:b alpha:alpha];
}
@end
在AppDelegate.h我宣告了兩個名為and的ColorView屬性,而在:leftViewrightViewAppDelegate.m
@synthesize leftView;
@synthesize rightView;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
leftView.translatesAutoresizingMaskIntoConstraints = NO;
rightView.translatesAutoresizingMaskIntoConstraints = NO;
NSView *view = [self.window contentView];
[self.window setBackgroundColor:[NSColor systemMintColor]];
if (view) {
[view addSubview:leftView];
[view addSubview:rightView];
[NSLayoutConstraint activateConstraints:@[
[leftView.topAnchor constraintEqualToAnchor:[view topAnchor]],
[leftView.leftAnchor constraintEqualToAnchor:[view leftAnchor]],
[leftView.rightAnchor constraintEqualToAnchor:[view centerXAnchor]],
[leftView.widthAnchor constraintGreaterThanOrEqualToConstant:150],
[leftView.heightAnchor constraintEqualToConstant:100],
[rightView.centerXAnchor constraintEqualToAnchor:[view centerXAnchor] constant:50],
[rightView.centerYAnchor constraintEqualToAnchor:[view centerYAnchor]],
[rightView.widthAnchor constraintEqualToConstant:100],
[rightView.heightAnchor constraintEqualToConstant:100]
]];
}
}
我還查看了存盤在此處的 NSView 子類化的存檔檔案,但其中大部分要么沒有編譯,要么沒有以有意義的方式提供幫助。
你能告訴我這段代碼哪里錯了,或者我錯過了什么嗎?如果標題不適合該問題,也請糾正我。
太感謝了
uj5u.com熱心網友回復:
在示例代碼中leftView,rightView從未分配過。
添加leftView=[[ColorView alloc]initWithFrame:someRect];(和類似的rightView)應該使代碼作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496059.html
