Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách khóa hướng màn hình (Screen Orientation) bằng code trong iOS

Đôi khi cần ép giao diện chỉ hiển thị ở một hướng cụ thể: Portrait (dọc) hoặc Landscape (ngang).

Cách khóa orientation bằng code (Swift)

Trong ViewController.swift, override 2 property:

// 1. Tắt auto-rotate
override var shouldAutorotate: Bool {
    return false
}

// 2. Chỉ định orientation được hỗ trợ
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait // Chỉ portrait
    // return .landscape // Chỉ landscape
    // return .portraitUpsideDown // Portrait ngược
    // return .all // Tất cả (mặc định)
}

Cách khóa hướng màn hình (Screen Orientation) bằng code trong iOS

Áp dụng cho toàn app (AppDelegate / SceneDelegate)

Nếu muốn khóa orientation cho toàn bộ ứng dụng, cấu hình trong Deployment Info của Target:

  1. Chọn Project → Target → General → Deployment Info
  2. Bỏ tick các orientation không muốn hỗ trợ
  3. Chỉ giữ Portrait (hoặc Landscape)

Cách khóa hướng màn hình (Screen Orientation) bằng code trong iOS

Khóa orientation cho từng ViewController riêng biệt

Mỗi VC có thể override khác nhau:

// VC1: Chỉ Portrait
class PortraitVC: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    override var shouldAutorotate: Bool { return false }
}

// VC2: Chỉ Landscape
class LandscapeVC: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscape
    }
    override var shouldAutorotate: Bool { return true } // Cho phép rotate vào landscape
}

// VC3: Tất cả
class FlexibleVC: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
}

Ép buộc rotate khi push/present VC (iOS 16+)

// Ép landscape khi present
let vc = LandscapeVC()
vc.modalPresentationStyle = .fullScreen
// iOS 16+
if #available(iOS 16.0, *) {
    vc.setNeedsUpdateOfSupportedInterfaceOrientations()
}
present(vc, animated: true)

// Hoặc dùng UINavigationController subclass
class CustomNavController: UINavigationController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }
    override var shouldAutorotate: Bool {
        return topViewController?.shouldAutorotate ?? false
    }
}

Lưu ý

  • shouldAutorotate = false + supportedInterfaceOrientations = .portrait = khóa hoàn toàn
  • iPad: Tuy nhiên iPad thường hỗ trợ multitasking, có thể override behavior
  • Info.plist: Key UISupportedInterfaceOrientations cũng ảnh hưởng (Deployment Info tự cập nhật key này)
  • Test trên thiết bị thật - simulator đôi khi hành vi khác