安全区域与iOS9 / 10/11兼容 - 以编程方式

时间:2018-06-14 13:54:55

标签: ios swift constraints

我想创建一个函数,在底部返回一个安全锚。 当我使用这样的(扩展UIViewController)

FileStream fStream = new FileStream("C:\\Program Files (x86)\\theAPPSettings\\ProtectedSettings.dat", FileMode.Open);

byte[] entropy = UnicodeEncoding.ASCII.GetBytes("A Shared Phrase between the encryption and decryption");

// Read from the stream and decrypt the data.
byte[] decryptData = Protection.DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, fStream, Length_of_Stream);

fStream.Close();

string temp = UnicodeEncoding.ASCII.GetString(decryptData);

我没有获得安全区域,因为我的标签栏覆盖了我的视图(仅限iOS9 / 10)。有人可以帮助解决这个问题吗? 用法:

//
var safeBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
        return view.safeAreaLayoutGuide.bottomAnchor
    } else {
        return bottomLayoutGuide.topAnchor
    }
}

1 个答案:

答案 0 :(得分:0)

这就是我的所作所为。基本上我创造了一个清晰的颜色"安全区域视图"并将我的所有布局都基于它。

在任何视图控制器中:

let safeAreaView = UIView()

override func viewDidLoad() {
    super.viewDidLoad()

    safeAreaView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(safeAreaView)

    if #available(iOS 11, *) {
        safeAreaView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        safeAreaView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        safeAreaView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        safeAreaView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    } else {
        safeAreaView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true
        safeAreaView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true
        safeAreaView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        safeAreaView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
    }

现在,如果您有一个名为mySubview的视图,并且您希望它在高度为40的导航栏下方10点,那么约束代码可以是:

    mySubview.topAnchor.constraint(equalTo: safeAreaView.topAnchor, constant: 10).isActive = true
    mySubview.leadingAnchor.constraint(equalTo: safeAreaView.leadingAnchor).isActive = true
    mySubview.trailingAnchor.constraint(equalTo: safeAreaView.trailingAnchor).isActive = true
    mySubview.heightAnchor.constraint(equalToConstant: 40).isActive = true

这适用于iOS 9以上的所有iOS版本。

最后一点 - 也许您的问题仅仅是您使用的是bottomLayoutGuide而不是layoutMarginsGuide.bottomAnchor