You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在iOS Swift应用的ViewController中实现多视图分屏显示

单个ViewController实现地图+底部信息分屏方案

完全可以用单个ViewController实现这个需求,不用额外控制器,核心就是在当前ViewController的主视图里添加两个子视图(地图视图+信息视图),控制它们的布局和显示状态就行,具体实现步骤和代码如下:

实现思路

  • 调整地图布局:把地图视图的范围限制在屏幕上半部分,不再占满整个屏幕
  • 提前创建信息视图:做一个专用于展示marker信息的视图,初始设为隐藏,放在屏幕下半区
  • 绑定点击事件:点击marker时,把对应数据填充到信息视图并显示出来

修改后的完整代码

import UIKit
import GoogleMaps

class ViewController: UIViewController, GMSMapViewDelegate {
    // 全局声明视图,方便后续操作
    private var mapView: GMSMapView!
    private var infoView: UIView!
    private var titleLabel: UILabel!
    private var snippetLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        GMSServices.provideAPIKey("My API Key")
        
        // 1. 初始化地图视图,仅占屏幕上半部分
        let mapFrame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height / 2)
        let camera = GMSCameraPosition.camera(withLatitude: 37.0902, longitude: -95.7129, zoom: 3.2)
        mapView = GMSMapView.map(withFrame: mapFrame, camera: camera)
        mapView.delegate = self
        view.addSubview(mapView)
        
        // 2. 搭建底部信息视图
        setupInfoView()
        
        // 添加测试标记
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 37.0902, longitude: -95.7129)
        marker.title = "美国本土"
        marker.snippet = "北纬37.0902,西经95.7129"
        marker.map = mapView
    }
    
    private func setupInfoView() {
        // 信息视图占屏幕下半部分
        infoView = UIView(frame: CGRect(x: 0, y: view.bounds.height / 2, width: view.bounds.width, height: view.bounds.height / 2))
        infoView.backgroundColor = .white
        infoView.layer.borderWidth = 1
        infoView.layer.borderColor = UIColor.lightGray.cgColor
        // 默认隐藏
        infoView.isHidden = true
        view.addSubview(infoView)
        
        // 添加标题标签
        titleLabel = UILabel(frame: CGRect(x: 20, y: 20, width: infoView.bounds.width - 40, height: 30))
        titleLabel.font = .boldSystemFont(ofSize: 18)
        infoView.addSubview(titleLabel)
        
        // 添加详情标签
        snippetLabel = UILabel(frame: CGRect(x: 20, y: 60, width: infoView.bounds.width - 40, height: 40))
        snippetLabel.font = .systemFont(ofSize: 14)
        snippetLabel.numberOfLines = 0
        infoView.addSubview(snippetLabel)
    }
    
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        // 填充标记信息到视图
        titleLabel.text = marker.title
        snippetLabel.text = marker.snippet
        // 显示信息视图
        infoView.isHidden = false
        return true
    }
}

可选优化点

  • 若要适配屏幕旋转,建议用Auto Layout约束替代固定frame,布局会更灵活
  • 可以给信息视图添加滑入动画,提升交互体验
  • 可补充地图空白处点击事件,用来隐藏信息视图

内容的提问来源于stack exchange,提问作者Derithus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:15:43