在我下面显示的swift 3程序中,我想在计算的初始化程序中访问计算变量'darkColor'。但swift 3编译器给我一个错误:实例成员'darkColor'不能用于'LoginViewController'类型
import UIKit
class LoginViewController: BaseViewController, UITextFieldDelegate {
// FIXME: - computed variables
private var darkColor: UIColor {
return UIColor(hex: 0x0083C5, alpha: 1)
}
// FIXME: - create views / computed initializers
lazy var textEmail: UITextField = {
let textField = UITextField()
textField.placeholder = "Email"
textField.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
textField.textColor = darkColor // here I'm getting error that "instance member 'darkColor' cannot be used on type 'LoginViewController'"
textField.keyboardType = .emailAddress
textField.autocorrectionType = .no
textField.translatesAutoresizingMaskIntoConstraints = false
textField.delegate = self
return textField
}()
let emailUnderline: UIView = {
let view = UIView()
view.backgroundColor = darkColor // here I'm getting error that "instance member 'darkColor' cannot be used on type 'LoginViewController'"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// FIXME: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
}
答案 0 :(得分:1)
在计算变量init
期间,几乎没有可能的方法self.darkColor
变量使用lazy
,因为它只会在访问时创建(在初始化类时无法访问self
)LoginViewController
let darkColor {...}
移到课程范围之外会使其成为全局常量答案 1 :(得分:0)
感谢@ Tj3n给我提示。我找到了4个解决这个问题的方法。其中3人来自Tj3n。
解决方案1 - 为常量使用不同的类
解决方案2 - 使用class var而不是var
int num = 1;
object arg;
bool flag = arg = num as object != null;
if (!flag)
{
arg = null;
}
Console.WriteLine("This should NOT be in scope:" + arg);
解决方案3 - 使用static let而不是var
class var darkColor: UIColor {
return UIColor(hex: 0x0083C5, alpha: 1)
}
解决方案4 - 对于惰性var类型的计算变量使用self.darkColor。 例如,
static let darkColor: UIColor = {
return UIColor(hex: 0x0083C5, alpha: 1)
}()