通用应用中 iPad 的 UI 完全不同

Completely different UI for iPad in a universal app

我通常将自动布局与尺寸 类 一起使用,以针对更大的屏幕优化 UI,例如 iPad。

但是,有时我需要 iPad 上的 UI 完全不同的布局,仍然包含相同的视图控制器,但结构不同。

在这种情况下,自动布局和大小 类 不够用的最佳策略是什么?正在为 iPad?

加载不同的故事板

显然这里的目标是不引入任何代码重复。

谢谢

我在 UIViews 和 NSLayoutConstraints 上对大小 类 做同样的事情,例如,如果我对 pad 和 phone 有不同的视图,但我必须对部分做同样的逻辑,我创建了两个同一故事板中的不同视图和 enable/disable 视图基于大小 类

在一个 class 文件中使用 2 个视图 (xib)。两个 xib 中的连接数必须相同,但 iPad 和 iPhone.

的元素放置可以不同

下面是我从 viewcontroller.

加载 XIB 的代码
class ViewController: UIViewController {

var customView:CustomView?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    loadCustomView()
}

func loadCustomView(){
    if  let appDelegate =  UIApplication.shared.delegate as? AppDelegate,
        let window = appDelegate.window {
        customView = CustomView(frame: CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height))
        window.addSubview(customView!)
    }
}
}

然后是UIView Class

import UIKit

class CustomView: UIView {

@IBOutlet weak var lbl_Title: UILabel!

var view:UIView!

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    setup()
}

func setup() {

    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = UIView.AutoresizingMask.flexibleWidth
    view.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
    addSubview(view)
}

func loadViewFromNib() -> UIView {
    if UIDevice.current.userInterfaceIdiom == .phone{
        let bundle = Bundle(for:type(of: self))
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        return view
    }else{
        let bundle = Bundle(for:type(of: self))
        let nib = UINib(nibName: "CustomViewTab", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        return view
    }

}
}

您从此 class 与两个 XIB 建立出口连接,并根据设备类型加载视图。

Loading a different storyboard for iPad? Obviously the goal here is to not introduce any code duplication.

如果这就是您想要做的,那么该功能是内置的并且是预期的。您根本不需要任何代码。只需创建您的两个故事板并编辑 Info.plist 以便它有两个指向它们的主要故事板条目:

正确的事情会发生:在 iPad,第二个故事板将在启动时加载。