首页
/ HXPhotoPicker中PhotoBrowser自定义与屏幕旋转实践

HXPhotoPicker中PhotoBrowser自定义与屏幕旋转实践

2025-06-25 00:17:09作者:魏侃纯Zoe

前言

HXPhotoPicker是一款功能强大的iOS照片选择器组件,其中PhotoBrowser模块提供了图片浏览功能。在实际开发中,我们经常需要对PhotoBrowser进行深度定制以满足业务需求。本文将详细介绍如何自定义PhotoBrowser的页面指示器、标题视图以及处理屏幕旋转逻辑。

自定义页面指示器

PhotoBrowser默认提供了页面指示器,但开发者可以通过实现PhotoBrowserPageIndicator协议来自定义样式。以下是实现自定义页面指示器的关键步骤:

  1. 创建自定义指示器类: 继承UIView并实现PhotoBrowserPageIndicator协议,该协议要求实现以下方法:

    • reloadData(numberOfPages: Int, pageIndex: Int) - 加载数据时调用
    • didChanged(pageIndex: Int) - 页面切换时调用
  2. 示例实现

    class CustomPageIndicator: UIView, PhotoBrowserPageIndicator {
        private let pageLabel = UILabel()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func setupUI() {
            pageLabel.textColor = .white
            pageLabel.textAlignment = .center
            addSubview(pageLabel)
        }
        
        func reloadData(numberOfPages: Int, pageIndex: Int) {
            updateText(currentPage: pageIndex, totalPages: numberOfPages)
        }
        
        func didChanged(pageIndex: Int) {
            updateText(currentPage: pageIndex)
        }
        
        private func updateText(currentPage: Int, totalPages: Int? = nil) {
            if let total = totalPages {
                pageLabel.text = "\(currentPage + 1)/\(total)"
            } else {
                let components = pageLabel.text?.components(separatedBy: "/")
                if let first = components?.first {
                    pageLabel.text = "\(currentPage + 1)/\(first)"
                }
            }
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            pageLabel.frame = bounds
        }
    }
    
  3. 设置自定义指示器

    let browser = PhotoBrowser(config: config, pageIndex: 0, assets: assets)
    browser.pageIndicator = CustomPageIndicator(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
    

自定义标题视图

PhotoBrowser的导航栏标题视图也可以自定义:

  1. 创建自定义标题视图

    class CustomTitleView: UIView {
        let titleLabel = UILabel()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            titleLabel.textColor = .white
            titleLabel.textAlignment = .center
            addSubview(titleLabel)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            titleLabel.frame = bounds
        }
    }
    
  2. 设置标题视图

    let titleView = CustomTitleView(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
    browser.previewViewController?.navigationItem.titleView = titleView
    

处理屏幕旋转

在图片浏览器中实现屏幕旋转功能需要注意以下几点:

  1. 配置旋转支持

    browser.config.shouldAutorotate = true
    browser.config.supportedInterfaceOrientations = .all
    
  2. 实现旋转控制

    enum DeviceOrientationHelper {
        static func setInterfaceOrientation(_ orientation: UIInterfaceOrientation) {
            if #available(iOS 16.0, *) {
                guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
                let orientationMask: UIInterfaceOrientationMask
                switch orientation {
                case .portrait: orientationMask = .portrait
                case .landscapeLeft: orientationMask = .landscapeLeft
                case .landscapeRight: orientationMask = .landscapeRight
                case .portraitUpsideDown: orientationMask = .portraitUpsideDown
                default: orientationMask = .allButUpsideDown
                }
                let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: orientationMask)
                scene.requestGeometryUpdate(geometryPreferences)
            } else {
                UIDevice.current.setValue(orientation.rawValue, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }
        }
        
        static var isLandscape: Bool {
            UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false
        }
    }
    
  3. 在自定义指示器中添加旋转按钮

    let rotateButton = UIButton()
    rotateButton.setTitle("旋转", for: .normal)
    rotateButton.addTarget(self, action: #selector(rotateScreen), for: .touchUpInside)
    
    @objc private func rotateScreen() {
        if DeviceOrientationHelper.isLandscape {
            DeviceOrientationHelper.setInterfaceOrientation(.portrait)
        } else {
            DeviceOrientationHelper.setInterfaceOrientation(.landscapeRight)
        }
    }
    

自定义返回按钮行为

如果需要自定义左上角返回按钮的行为(例如在横屏时先返回竖屏),可以通过以下方式实现:

  1. 替换返回按钮事件

    browser.show(nil)
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
        let item = browser.previewViewController?.navigationItem.leftBarButtonItem
        item?.action = #selector(self.customBackAction)
        item?.target = self
    }
    
  2. 实现自定义返回逻辑

    @objc private func customBackAction() {
        if DeviceOrientationHelper.isLandscape {
            DeviceOrientationHelper.setInterfaceOrientation(.portrait)
        } else {
            browser.previewViewController?.dismiss(animated: true)
        }
    }
    

总结

通过对HXPhotoPicker中PhotoBrowser模块的自定义,我们可以实现更加符合业务需求的图片浏览器功能。关键点包括:

  1. 通过实现PhotoBrowserPageIndicator协议自定义页面指示器
  2. 直接替换导航栏的titleView来自定义标题显示
  3. 使用系统API处理屏幕旋转逻辑
  4. 通过替换返回按钮事件实现自定义返回逻辑

这些定制方法不仅适用于HXPhotoPicker,其思路也可以应用于其他类似的图片浏览器组件中。开发者可以根据实际需求灵活组合这些技术点,打造出功能丰富、用户体验良好的图片浏览功能。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
858
511
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
258
298
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
83
4
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
kernelkernel
deepin linux kernel
C
22
5