- 创建行程

行程点的地图选择、搜索功能
	行程点的路线绘制
This commit is contained in:
linshujie 2026-06-24 18:42:14 +08:00
parent 0a1c309ad1
commit c3228c5e36
22 changed files with 1270 additions and 143 deletions

View File

@ -60,8 +60,9 @@ target 'QuickLocation' do
pod 'WechatOpenSDK-XCFramework'
#高德地图
pod 'AMapNavi-NO-IDFA' #导航SDK(含地图+搜索+导航)
pod 'AMapNavi-NO-IDFA' #导航SDK
pod 'AMapLocation-NO-IDFA' #定位SDK
pod 'AMapSearch-NO-IDFA' #搜索SDK
end

View File

@ -6,6 +6,8 @@ PODS:
- AMapFoundation-NO-IDFA (>= 1.9.0)
- AMapNavi-NO-IDFA (11.2.000):
- AMapFoundation-NO-IDFA (>= 1.9.0)
- AMapSearch-NO-IDFA (9.8.0):
- AMapFoundation-NO-IDFA (>= 1.9.0)
- BRPickerView (3.0.0):
- BRPickerView/Default (= 3.0.0)
- BRPickerView/Core (3.0.0)
@ -188,6 +190,7 @@ DEPENDENCIES:
- AlipaySDK-iOS
- AMapLocation-NO-IDFA
- AMapNavi-NO-IDFA
- AMapSearch-NO-IDFA
- BRPickerView
- CocoaLumberjack/Swift
- CocoaMQTT
@ -231,6 +234,7 @@ SPEC REPOS:
- AMapFoundation-NO-IDFA
- AMapLocation-NO-IDFA
- AMapNavi-NO-IDFA
- AMapSearch-NO-IDFA
- BRPickerView
- CocoaLumberjack
- CocoaMQTT
@ -296,6 +300,7 @@ SPEC CHECKSUMS:
AMapFoundation-NO-IDFA: a2e3c895398d7ee757278e1a0a8f9359da4b146e
AMapLocation-NO-IDFA: 7cd8fc837ea41edfbf4d937cd20572e277b77d18
AMapNavi-NO-IDFA: d55b9b138c6e540f737c689975cae2c9dbd1026a
AMapSearch-NO-IDFA: c0afd2a69a076d4228becda4401dbe4a279a03ef
BRPickerView: cd2e0e3aa87af062bc7a1b6f78d3dfd5f04f04bb
CocoaLumberjack: e4ba3b414dfca8c1916c6303d37f63b3a95134c6
CocoaMQTT: 1e2fa493d57045d66fb1eba2bb5ffb8d77039c60
@ -347,6 +352,6 @@ SPEC CHECKSUMS:
YYImage: 1e1b62a9997399593e4b9c4ecfbbabbf1d3f3b54
ZXSDK: 786338c0a18e98e03eda00699c3bfd2700b97117
PODFILE CHECKSUM: 848cd9ba02b2f1c209ac9eef708dd2c43b005385
PODFILE CHECKSUM: 55d478000a8bba48e7bb7de252ef246a0b3784c4
COCOAPODS: 1.16.2

View File

@ -206,6 +206,9 @@
30D74ABD2FEA67EA0050EB2C /* CreateScheduleVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74ABC2FEA67EA0050EB2C /* CreateScheduleVC.swift */; };
30D74ABF2FEA67F30050EB2C /* CreateScheduleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74ABE2FEA67F30050EB2C /* CreateScheduleView.swift */; };
30D74AC12FEA6EEF0050EB2C /* CreateSchedulePopView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74AC02FEA6EEF0050EB2C /* CreateSchedulePopView.swift */; };
30D74BF32FEB6F5B0050EB2C /* LocationPickerVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74BF02FEB6F5B0050EB2C /* LocationPickerVC.swift */; };
30D74BF42FEB6F5B0050EB2C /* LocationPickerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74BF12FEB6F5B0050EB2C /* LocationPickerView.swift */; };
30D74D1F2FEBB09B0050EB2C /* CreateScheduleVM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D74D1E2FEBB09B0050EB2C /* CreateScheduleVM.swift */; };
30D87CDB2FDFA9EE00E958FD /* MQTTService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDA2FDFA9EE00E958FD /* MQTTService.swift */; };
30D87CDD2FDFF07500E958FD /* InteractionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDC2FDFF07500E958FD /* InteractionView.swift */; };
30D87CDF2FDFF1A100E958FD /* QuickMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30D87CDE2FDFF1A100E958FD /* QuickMessageView.swift */; };
@ -463,6 +466,9 @@
30D74ABC2FEA67EA0050EB2C /* CreateScheduleVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateScheduleVC.swift; sourceTree = "<group>"; };
30D74ABE2FEA67F30050EB2C /* CreateScheduleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateScheduleView.swift; sourceTree = "<group>"; };
30D74AC02FEA6EEF0050EB2C /* CreateSchedulePopView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateSchedulePopView.swift; sourceTree = "<group>"; };
30D74BF02FEB6F5B0050EB2C /* LocationPickerVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationPickerVC.swift; sourceTree = "<group>"; };
30D74BF12FEB6F5B0050EB2C /* LocationPickerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationPickerView.swift; sourceTree = "<group>"; };
30D74D1E2FEBB09B0050EB2C /* CreateScheduleVM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateScheduleVM.swift; sourceTree = "<group>"; };
30D87CDA2FDFA9EE00E958FD /* MQTTService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MQTTService.swift; sourceTree = "<group>"; };
30D87CDC2FDFF07500E958FD /* InteractionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InteractionView.swift; sourceTree = "<group>"; };
30D87CDE2FDFF1A100E958FD /* QuickMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuickMessageView.swift; sourceTree = "<group>"; };
@ -519,29 +525,21 @@
/* Begin PBXFileSystemSynchronizedRootGroup section */
30CCDF8E2FE3E63B00F5214A /* sound */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = sound;
sourceTree = "<group>";
};
30CCDF902FE3E63B00F5214A /* video */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = video;
sourceTree = "<group>";
};
30CCE01E2FE3E64700F5214A /* lotties */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = lotties;
sourceTree = "<group>";
};
30D87CEF2FDFF52100E958FD /* TTGTagCollectionView */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
);
path = TTGTagCollectionView;
sourceTree = "<group>";
};
@ -1284,6 +1282,7 @@
30D74AB32FEA25B90050EB2C /* ViewedModel.swift */,
30D74AB92FEA37AD0050EB2C /* ScheduleModel.swift */,
30D74ABB2FEA67CE0050EB2C /* CreateSchedule */,
30D74BF22FEB6F5B0050EB2C /* LocationPicker */,
);
path = Schedule;
sourceTree = "<group>";
@ -1292,12 +1291,22 @@
isa = PBXGroup;
children = (
30D74ABC2FEA67EA0050EB2C /* CreateScheduleVC.swift */,
30D74D1E2FEBB09B0050EB2C /* CreateScheduleVM.swift */,
30D74ABE2FEA67F30050EB2C /* CreateScheduleView.swift */,
30D74AC02FEA6EEF0050EB2C /* CreateSchedulePopView.swift */,
);
path = CreateSchedule;
sourceTree = "<group>";
};
30D74BF22FEB6F5B0050EB2C /* LocationPicker */ = {
isa = PBXGroup;
children = (
30D74BF02FEB6F5B0050EB2C /* LocationPickerVC.swift */,
30D74BF12FEB6F5B0050EB2C /* LocationPickerView.swift */,
);
path = LocationPicker;
sourceTree = "<group>";
};
30D87CD52FDF9F1900E958FD /* MQTT */ = {
isa = PBXGroup;
children = (
@ -1555,10 +1564,14 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-frameworks.sh\"\n";
@ -1572,10 +1585,14 @@
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources-${CONFIGURATION}-input-files.xcfilelist",
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources-${CONFIGURATION}-output-files.xcfilelist",
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-QuickLocation/Pods-QuickLocation-resources.sh\"\n";
@ -1611,11 +1628,14 @@
305A76942FCA8C7000227D26 /* UploadImageCell.swift in Sources */,
305A76952FCA8C7000227D26 /* CornerRadiusCell.swift in Sources */,
305A76962FCA8C7000227D26 /* CornerRadiusFooterView.swift in Sources */,
30D74BF32FEB6F5B0050EB2C /* LocationPickerVC.swift in Sources */,
30D74BF42FEB6F5B0050EB2C /* LocationPickerView.swift in Sources */,
30C4C0162FDB91B8009215C1 /* CheckPermissionVC.swift in Sources */,
305A76972FCA8C7000227D26 /* CornerRadiusHeaderView.swift in Sources */,
305A76982FCA8C7000227D26 /* ImagePicker.swift in Sources */,
305A76992FCA8C7000227D26 /* ImagePickerPopup.swift in Sources */,
30EFF3E22FDA9DEE00EB35D4 /* EmergencyContactVM.swift in Sources */,
30D74D1F2FEBB09B0050EB2C /* CreateScheduleVM.swift in Sources */,
305A769A2FCA8C7000227D26 /* PopupAnimator.swift in Sources */,
3062E8BE2FCEBD0E00CEF511 /* GroupIconListVC.swift in Sources */,
30EFF3DA2FDA935D00EB35D4 /* EmergencyContactFooterView.swift in Sources */,

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Group_2289@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Group_2289@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 694 B

View File

@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Group_1584@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Group_1584@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -12,6 +12,7 @@ import SwiftyUserDefaults
extension DefaultsKeys {
/// 当前经纬度
var currentLatitude: DefaultsKey<Double?> { .init("currentLatitude") }
var currentLongitude: DefaultsKey<Double?> { .init("currentLongitude") }
/// 是否自动更新位置
var updateLocationEnable: DefaultsKey<Bool> { .init("updateLocationEnable", defaultValue: true) }
/// 是否从第三方应用跳回

View File

@ -345,3 +345,15 @@ extension UIView {
return dateString
}
}
extension UIView {
var parentViewController: UIViewController? {
var responder: UIResponder? = self
while let next = responder?.next {
if let vc = next as? UIViewController { return vc }
responder = next
}
return nil
}
}

View File

@ -45,7 +45,7 @@ class HomeView: UIView {
// MARK: - Map
#if !targetEnvironment(simulator)
lazy var mapView: MAMapView = {
lazy var mapView: MAMapView! = {
let mv = MAMapView()
mv.zoomLevel = 16
mv.showsUserLocation = true

View File

@ -417,7 +417,8 @@ class HomeViewController: BaseViewController {
// 从 members 中过滤出在线成员用于地图标注
let onlineMembers = newMembers.filter { $0.isOnline }
let mapView = rootView.mapView
guard let mapView = rootView.mapView else { return }
let existing = mapView.annotations?.compactMap { $0 as? MemberAnnotation } ?? []
let existingIDs = Set(existing.map { $0.member.id })
let onlineIDs = Set(onlineMembers.map { $0.id })
@ -660,7 +661,7 @@ extension HomeViewController {
/// 移除指定成员的标注
private func removeAnnotation(userId: String) {
#if !targetEnvironment(simulator)
let mapView = rootView.mapView
guard let mapView = rootView.mapView else { return }
let toRemove = mapView.annotations?.compactMap({ $0 as? MemberAnnotation }).filter { $0.member.id == userId }
if let remove = toRemove, !remove.isEmpty {
mapView.removeAnnotations(remove)
@ -684,7 +685,7 @@ extension HomeViewController {
}
// 更新地图标注
let mapView = rootView.mapView
guard let mapView = rootView.mapView else { return }
if let oldMember = members.first(where: { $0.id == userId }), oldMember.isOnline {
// 先移除旧标注,再添加新标注
let toRemove = mapView.annotations?.compactMap({ $0 as? MemberAnnotation }).filter { $0.member.id == userId }
@ -738,6 +739,8 @@ extension HomeViewController: MAMapViewDelegate {
// 地图标注
lastLocation = location
Defaults[\.currentLatitude] = location.coordinate.latitude
Defaults[\.currentLongitude] = location.coordinate.longitude
let coordinate = location.coordinate
guard CLLocationCoordinate2DIsValid(coordinate) else { return }

View File

@ -44,6 +44,15 @@ class NavigationVC: BaseViewController {
rootView = NavigationView(frame: UIScreen.main.bounds)
view = rootView
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// 页面被 pop/dismiss 时清理地图资源
if isMovingFromParent || isBeingDismissed {
#if !targetEnvironment(simulator)
rootView.cleanupMap()
#endif
}
}
override func viewDidLoad() {
super.viewDidLoad()

View File

@ -156,7 +156,7 @@ class NavigationView: UIView {
}()
#if !targetEnvironment(simulator)
lazy var mapView: MAMapView = {
lazy var mapView: MAMapView! = {
let mv = MAMapView()
mv.zoomLevel = 14
mv.showsUserLocation = false
@ -245,6 +245,15 @@ class NavigationView: UIView {
return label
}()
#if !targetEnvironment(simulator)
func cleanupMap() {
mapView?.delegate = nil
mapView?.removeFromSuperview()
mapView = nil
}
#endif
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear

View File

@ -10,99 +10,26 @@ import RxSwift
import RxCocoa
import RxDataSources
import BRPickerView
// MARK: - 行程点编辑模型
struct SchedulePointItem: IdentifiableType, Equatable {
let identity: String = UUID().uuidString
var locationName: String = ""
var address: String = ""
var expectedTime: Date?
var remark: String = ""
}
typealias SchedulePointSection = SectionModel<String, SchedulePointItem>
import RxGesture
import CoreLocation
import TagListView
// MARK: - CreateSchedulePopView
class CreateSchedulePopView: UIView {
var disposeBag = DisposeBag()
let pointsRelay = BehaviorRelay<[SchedulePointItem]>(value: [SchedulePointItem()])
// MARK: - Setup
private func setupRx() {
dateLab.rx.tapGesture.subscribe { _ in
let picker = BRDatePickerView(pickerMode: .YMD)
picker.minDate = Date()
picker.maxDate = Calendar.current.date(byAdding: .day, value: 6, to: Date())
let style = BRPickerStyle()
style.selectRowTextColor = UIColor(hexStr: "#16B3FF")
picker.pickerStyle = style
picker.resultBlock = { [weak self] selectDate, value in
guard let date = selectDate else { return }
let fmt = DateFormatter()
fmt.dateFormat = "yyyy年MM月dd日"
self?.dateLab.text = fmt.string(from: date)
}
picker.show()
}.disposed(by: disposeBag)
// 新增行程点
addBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
var list = self.pointsRelay.value
list.append(SchedulePointItem(
locationName: "",
address: "",
expectedTime: nil,
remark: ""
))
self.pointsRelay.accept(list)
})
.disposed(by: disposeBag)
// 绑定 tableView
pointsRelay
.observe(on: MainScheduler.asyncInstance)
.map { [SchedulePointSection(model: "", items: $0)] }
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
// 动态更新 tableView 高度
pointsRelay
.subscribe(onNext: { [weak self] items in
guard let self = self else { return }
let rowHeight: CGFloat = 122
var h = CGFloat(items.count) * rowHeight
h = max(h, rowHeight)
self.tableView.layoutChain.height(h)
})
.disposed(by: disposeBag)
func setupTagData(_ list: [GroupInfoModel]) {
let nameArr = list.map { $0.name }
tagListView.removeAllTags()
tagListView.addTags(nameArr)
tagListView.tagViews.forEach {
$0.layer.cornerRadius = 4
}
tagListView.invalidateIntrinsicContentSize() // 通知系统重新算高
}
private lazy var dataSource: RxTableViewSectionedReloadDataSource<SchedulePointSection> = {
RxTableViewSectionedReloadDataSource<SchedulePointSection>(
configureCell: { [weak self] _, tv, indexPath, item in
let cell: SchedulePointCell = tv.dequeueReusableCell(for: indexPath)
cell.configure(item: item,
index: indexPath.row,
total: self?.pointsRelay.value.count ?? 0,
onDelete: { [weak self] in
guard let self = self else { return }
var list = self.pointsRelay.value
guard indexPath.row < list.count else { return }
list.remove(at: indexPath.row)
self.pointsRelay.accept(list)
})
return cell
})
}()
// MARK: - UI
private func setupUI() {
addSubview(lineView)
addSubview(dateView)
@ -182,7 +109,7 @@ class CreateSchedulePopView: UIView {
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "Schedule/add"), for: .normal)
btn.backgroundColor = .clear
btn.extendEdgeInsets = UIEdgeInsets(top: 30, left: 10, bottom: 10, right: 15)
btn.extendEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 10, right: 15)
return btn
}()
@ -191,6 +118,7 @@ class CreateSchedulePopView: UIView {
view.backgroundColor = .white
view.showsHorizontalScrollIndicator = false
view.bounces = false
view.delaysContentTouches = false
let contentView = UIView()
contentView.backgroundColor = .clear
@ -203,9 +131,14 @@ class CreateSchedulePopView: UIView {
.top()
.edgesHorzontal()
contentView.addSubview(shareGroupView)
shareGroupView.layoutChain
.topToBottomOfView(tableView, offset: 5)
.edgesHorzontal()
contentView.addSubview(createBtn)
createBtn.layoutChain
.topToBottomOfView(tableView, offset: 30)
.topToBottomOfView(shareGroupView, offset: 30)
.edgesHorzontal(30)
.height(50)
.bottom(kSafeBottomMargin + 10)
@ -225,6 +158,42 @@ class CreateSchedulePopView: UIView {
return tv
}()
/// 选择分享的圈子
lazy var shareGroupView: UIView = {
let view = UIView()
view.backgroundColor = .clear
let titleLab = UILabel()
titleLab.text = "选择分享的圈子"
titleLab.font = .systemFont(ofSize: 14, weight: .medium)
titleLab.textColor = ThemeManager.shared.color.titleAuxColor
view.addSubview(titleLab)
titleLab.layoutChain.left(15).top()
view.addSubview(tagListView)
tagListView.layoutChain
.topToBottomOfView(titleLab, offset: 15)
.edgesHorzontal(15)
.bottom(15)
return view
}()
lazy var tagListView: TagListView = {
let view = TagListView()
view.textFont = UIFont.systemFont(ofSize: 12, weight: .medium)
view.textColor = UIColor(hexStr: "#999999")
view.tagBackgroundColor = UIColor(hexStr: "#F2F2F2")
view.selectedTextColor = UIColor(hexStr: "#16B3FF")
view.tagSelectedBackgroundColor = UIColor(hexStr: "#E3F6FF")
view.selectedBorderColor = UIColor(hexStr: "#16B3FF")
view.paddingX = 15 // 水平内边距
view.paddingY = 10 // 垂直内边距
view.alignment = .left // 对齐
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var createBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("立即创建", for: .normal)
@ -239,7 +208,6 @@ class CreateSchedulePopView: UIView {
super.init(frame: frame)
backgroundColor = .white
setupUI()
setupRx()
}
required init?(coder: NSCoder) {
@ -253,23 +221,40 @@ class CreateSchedulePopView: UIView {
}
}
// MARK: - SchedulePointCell
class SchedulePointCell: UITableViewCell {
var disposeBag = DisposeBag()
var onLocationTap: (() -> Void)?
var onTimeTap: (() -> Void)?
func configure(item: SchedulePointItem, index: Int, total: Int, onDelete: @escaping () -> Void) {
disposeBag = DisposeBag()
indexLabel.text = "\(index + 1)"
locationLabel.text = item.locationName.isEmpty ? "点击选择地点" : item.locationName
locationLabel.rx.tapGesture
.when(.recognized)
.subscribe(onNext: { [weak self] _ in
self?.onLocationTap?()
})
.disposed(by: disposeBag)
if let expectedTime = item.expectedTime {
timeLabel.text = formatTime(expectedTime)
}
else {
} else {
timeLabel.text = "请选择到达时间"
}
timeLabel.rx.tapGesture
.when(.recognized)
.subscribe(onNext: { [weak self] _ in
self?.onTimeTap?()
})
.disposed(by: disposeBag)
// 左侧竖线:仅有一条时不显示虚线,首条顶部不画、末条底部不画
topDashView.isHidden = total <= 1 || index == 0
@ -334,7 +319,7 @@ class SchedulePointCell: UITableViewCell {
.top(15)
.leftToRightOfView(pointIcon, offset: 20)
.right(15)
.height(92)
// .height(92)
.bottom(15)
cardCornerView.layoutChain.edges()
@ -346,19 +331,26 @@ class SchedulePointCell: UITableViewCell {
locationLabel.layoutChain
.topToBottomOfView(indexLabel, offset: 10)
.left(10)
.compressionHorizontal(.defaultLow)
timeLabel.layoutChain
.centerY(locationLabel)
.leftToRightOfView(locationLabel, offset: 38)
.topToView(locationLabel)
.right(10)
.compressionHorizontal(.required)
locationLabel.layoutChain.rightToLeftOfView(timeLabel, offset: -8)
deleteBtn.layoutChain
.bottom(15).right(15)
.right(15)
.width(14).height(14)
remarkTF.layoutChain
.topToBottomOfView(locationLabel, offset: 15)
.leftToView(locationLabel)
.rightToLeftOfView(deleteBtn, offset: -10)
.bottom(15)
deleteBtn.layoutChain.centerY(remarkTF)
}
// MARK: - Views
@ -412,7 +404,7 @@ class SchedulePointCell: UITableViewCell {
let l = UILabel()
l.font = .systemFont(ofSize: 14, weight: .medium)
l.textColor = UIColor(hexStr: "#333333")
l.lineBreakMode = .byTruncatingTail
// l.numberOfLines = 0
return l
}()
@ -421,6 +413,7 @@ class SchedulePointCell: UITableViewCell {
l.font = .systemFont(ofSize: 12, weight: .medium)
l.textColor = UIColor(hexStr: "#333333")
l.isUserInteractionEnabled = true
l.textAlignment = .right
return l
}()

View File

@ -6,31 +6,403 @@
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import SwiftyUserDefaults
import BRPickerView
import RxGesture
class CreateScheduleVC: BaseViewController {
#if !targetEnvironment(simulator)
import AMapNaviKit
import AMapSearchKit
import TagListView
#endif
class CreateScheduleVC: BaseViewController, MAMapViewDelegate {
override var isNavigationBarHidden: Bool { true }
fileprivate var rootView: CreateScheduleView!
private let viewModel = CreateScheduleVM()
private var popView: CreateSchedulePopView { rootView.createSchedulePopView }
override func loadView() {
rootView = CreateScheduleView(frame: UIScreen.main.bounds)
view = rootView
}
private var groupList: [GroupInfoModel] = []
override func viewDidLoad() {
super.viewDidLoad()
popView.tagListView.delegate = self
setupMap()
bindViewModel()
// Do any additional setup after loading the view.
requestGroupInfo()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParent || isBeingDismissed {
#if !targetEnvironment(simulator)
rootView.cleanupMap()
#endif
}
}
*/
// MARK: - API
private func requestGroupInfo() {
GroupService.groupInfo().subscribe { response in
guard let model = response.model else { return }
self.groupList = model.groups
self.popView.setupTagData(model.groups)
}.disposed(by: disposeBag)
}
// MARK: - Binding
private lazy var dataSource: RxTableViewSectionedReloadDataSource<SchedulePointSection> = {
RxTableViewSectionedReloadDataSource<SchedulePointSection>(
configureCell: { [weak self] _, tv, indexPath, item in
let cell: SchedulePointCell = tv.dequeueReusableCell(for: indexPath)
cell.onTimeTap = { [weak self] in
guard let self = self else { return }
let picker = BRDatePickerView(pickerMode: .HM)
picker.title = "选择到达时间"
let style = BRPickerStyle()
style.selectRowTextColor = UIColor(hexStr: "#16B3FF")
picker.pickerStyle = style
picker.resultBlock = { date, _ in
guard let d = date else { return }
var list = self.viewModel.pointsRelay.value
guard indexPath.row < list.count else { return }
// 用今天的日期 + 选择的时间拼成完整时间戳
let cal = Calendar.current
let today = Date()
var comps = cal.dateComponents([.year, .month, .day], from: today)
let timeComps = cal.dateComponents([.hour, .minute], from: d)
comps.hour = timeComps.hour
comps.minute = timeComps.minute
if let merged = cal.date(from: comps) {
list[indexPath.row].expectedTime = merged
self.viewModel.pointsRelay.accept(list)
}
}
picker.show()
}
cell.onLocationTap = { [weak self] in
guard let self = self else { return }
let coord = item.latitude != 0 || item.longitude != 0
? CLLocationCoordinate2D(latitude: item.latitude, longitude: item.longitude)
: kCLLocationCoordinate2DInvalid
let vc = LocationPickerVC()
vc.modalPresentationStyle = .fullScreen
if !item.locationName.isEmpty {
vc.initialLocation = PickedLocation(
name: item.locationName, address: item.address,
coordinate: coord,
province: item.province, city: item.city,
district: item.district, street: item.street,
country: item.country, formatted_address: item.formatted_address
)
}
vc.onPickedLocation = { picked in
self.viewModel.updatePointLocation(index: indexPath.row, name: picked.name, address: picked.address)
// 补充坐标
var list = self.viewModel.pointsRelay.value
guard indexPath.row < list.count else { return }
list[indexPath.row].latitude = picked.coordinate.latitude
list[indexPath.row].longitude = picked.coordinate.longitude
self.viewModel.pointsRelay.accept(list)
}
self.present(vc, animated: true)
}
cell.configure(item: item, index: indexPath.row,
total: self?.viewModel.pointsRelay.value.count ?? 0,
onDelete: { [weak self] in
self?.viewModel.deletePointAt.onNext(indexPath.row)
})
return cell
})
}()
fileprivate func bindViewModel() {
// 日期
viewModel.dateString
.bind(to: popView.dateLab.rx.text)
.disposed(by: disposeBag)
// tableView
viewModel.pointsRelay
.map { [SchedulePointSection(model: "", items: $0)] }
.bind(to: popView.tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
// 动态高度 + 刷新地图路线
viewModel.pointsRelay
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] items in
guard let self = self else { return }
let h = max(CGFloat(items.count) * 122, 122)
self.popView.tableView.layoutChain.height(h)
self.refreshMapPoints()
})
.disposed(by: disposeBag)
// 添加
popView.addBtn.rx.tap
.bind(to: viewModel.addPointTapped)
.disposed(by: disposeBag)
// 日期点击
popView.dateLab.rx.tapGesture
.when(.recognized)
.subscribe(onNext: { [weak self] _ in
self?.showDatePicker()
})
.disposed(by: disposeBag)
// 创建行程
popView.createBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
self?.handleCreate()
})
.disposed(by: disposeBag)
}
private func handleCreate() {
let points = viewModel.pointsRelay.value
let hasLocation = points.filter { $0.latitude != 0 || $0.longitude != 0 }
let hasTime = points.filter { $0.expectedTime != nil }
// 校验
guard points.count >= 2 else { DLToast.show(text: "至少需要两个行程点"); return }
guard hasLocation.count == points.count else { DLToast.show(text: "请为每个行程点选择地点"); return }
guard hasTime.count == points.count else { DLToast.show(text: "请为每个行程点选择到达时间"); return }
guard !viewModel.selectedGroupKeys.isEmpty else { DLToast.show(text: "请选择分享的圈子"); return }
// 时间戳(毫秒)
let ts = Int64(viewModel.selectedDate.value.timeIntervalSince1970 * 1000)
// 生成 points 数组
let pointsJSON: [[String: Any]] = points.map { p in
let expectedTs = p.expectedTime.map { Int64($0.timeIntervalSince1970 * 1000) } ?? 0
return [
"point": ["lat": p.latitude, "lng": p.longitude],
"address": [
"formatted_address": p.formatted_address,
"country": p.country,
"province": p.province,
"city": p.city,
"district": p.district,
"street": p.street
],
"expected_timestamp": expectedTs,
"remark": p.remark
]
}
let params: [String: Any] = [
"group_keys": viewModel.selectedGroupKeys,
"timestamp": ts,
"points": pointsJSON
]
print("📋 Create schedule: \(params)")
DLToast.show(text: "创建成功")
}
private func setupMap() {
#if !targetEnvironment(simulator)
rootView.mapView.delegate = self
rootView.mapView.showsUserLocation = false
if let lat = Defaults[\.currentLatitude], let lon = Defaults[\.currentLongitude] {
let coord = CLLocationCoordinate2D(latitude: lat, longitude: lon)
if CLLocationCoordinate2DIsValid(coord) {
rootView.mapView.setCenter(coord, animated: false)
rootView.mapView.setZoomLevel(18, animated: false)
}
}
#endif
}
// MARK: - Date Picker
private func showDatePicker() {
let picker = BRDatePickerView(pickerMode: .YMD)
picker.minDate = Date()
picker.maxDate = Calendar.current.date(byAdding: .day, value: 7, to: Date())
let style = BRPickerStyle()
style.selectRowTextColor = UIColor(hexStr: "#16B3FF")
picker.pickerStyle = style
picker.resultBlock = { [weak self] date, _ in
if let d = date { self?.viewModel.selectedDate.accept(d) }
}
picker.show()
}
// MARK: - 路线规划
#if !targetEnvironment(simulator)
private let routeSearch = AMapSearchAPI()
#endif
private var routeOverlays: [MAPolyline] = []
private var pointAnnotations: [MAPointAnnotation] = []
/// 待规划的有效点队列(refreshMapPoints 先存点,异步回调解锁)
private var pendingRoutePoints: [CLLocationCoordinate2D] = []
private func refreshMapPoints() {
let points = viewModel.pointsRelay.value
#if !targetEnvironment(simulator)
routeSearch?.delegate = self
// 清除旧标注和路线
for ann in pointAnnotations { rootView.mapView.removeAnnotation(ann) }
for ol in routeOverlays { rootView.mapView.remove(ol) }
pointAnnotations.removeAll()
routeOverlays.removeAll()
// 添加带序号的标注
let validPoints = points.filter { $0.latitude != 0 || $0.longitude != 0 }
for (i, p) in validPoints.enumerated() {
let ann = MAPointAnnotation()
ann.coordinate = CLLocationCoordinate2D(latitude: p.latitude, longitude: p.longitude)
ann.title = "\(i + 1)"
rootView.mapView.addAnnotation(ann)
pointAnnotations.append(ann)
}
// 请求驾车路线
if validPoints.count >= 2 {
pendingRoutePoints = validPoints.map { CLLocationCoordinate2D(latitude: $0.latitude, longitude: $0.longitude) }
requestRoute()
}
// 缩放至包含所有点
let lats = validPoints.map { $0.latitude }
let lons = validPoints.map { $0.longitude }
if let minLat = lats.min(), let maxLat = lats.max(),
let minLon = lons.min(), let maxLon = lons.max() {
let center = CLLocationCoordinate2D(latitude: (minLat + maxLat) / 2, longitude: (minLon + maxLon) / 2)
let span = MACoordinateSpan(latitudeDelta: (maxLat - minLat) * 2.5 + 0.01, longitudeDelta: (maxLon - minLon) * 2.5 + 0.01)
rootView.mapView.setRegion(MACoordinateRegion(center: center, span: span), animated: true)
}
#endif
}
#if !targetEnvironment(simulator)
private func requestRoute() {
guard pendingRoutePoints.count >= 2 else { return }
let request = AMapDrivingRouteSearchRequest()
request.origin = AMapGeoPoint.location(withLatitude: CGFloat(pendingRoutePoints[0].latitude), longitude: CGFloat(pendingRoutePoints[0].longitude))
request.destination = AMapGeoPoint.location(withLatitude: CGFloat(pendingRoutePoints.last!.latitude), longitude: CGFloat(pendingRoutePoints.last!.longitude))
// 中间途经点
if pendingRoutePoints.count > 2 {
var waypoints: [AMapGeoPoint] = []
for i in 1..<pendingRoutePoints.count - 1 {
let p = pendingRoutePoints[i]
if let wp = AMapGeoPoint.location(withLatitude: CGFloat(p.latitude), longitude: CGFloat(p.longitude)) {
waypoints.append(wp)
}
}
request.waypoints = waypoints
}
request.strategy = 0
// request.city = ""
routeSearch?.aMapDrivingRouteSearch(request)
}
#endif
/// 生成数字图标
private static func numberImage(_ num: Int) -> UIImage? {
let size = CGSize(width: 20, height: 20)
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
// 白色边框
ctx.setLineWidth(1)
ctx.setStrokeColor(UIColor.white.cgColor)
// 蓝色填充
ctx.setFillColor(UIColor(hexStr: "#16B3FF").cgColor)
let path = UIBezierPath(ovalIn: rect)
path.fill()
path.stroke()
// 白色文字
let text = "\(num)" as NSString
let attrs: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 11), .foregroundColor: UIColor.white]
let strSize = text.size(withAttributes: attrs)
text.draw(at: CGPoint(x: (size.width - strSize.width) / 2, y: (size.height - strSize.height) / 2))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
// MARK: - Map
func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
guard !(annotation is MAUserLocation), let pointAnn = annotation as? MAPointAnnotation else { return nil }
if let num = Int(pointAnn.title ?? "") {
let id = "PointPin"
var view = mapView.dequeueReusableAnnotationView(withIdentifier: id)
if view == nil { view = MAAnnotationView(annotation: annotation, reuseIdentifier: id) }
else { view?.annotation = annotation }
view?.image = Self.numberImage(num)
view?.centerOffset = CGPoint(x: 0, y: -15)
return view
}
return nil
}
func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
if let polyline = overlay as? MAPolyline {
let r = MAPolylineRenderer(polyline: polyline)
r?.strokeColor = UIColor(hexStr: "#16B3FF")
r?.lineWidth = 3
r?.lineDashType = kMALineDashTypeSquare
return r
}
return nil
}
}
// MARK: - TagListViewDelegate
extension CreateScheduleVC: TagListViewDelegate {
func tagPressed(_ title: String, tagView: TagView, sender: TagListView) {
tagView.isSelected = !tagView.isSelected
// 根据 tagView 在 tagViews 中的索引获取对应的 group_key
guard let idx = sender.tagViews.firstIndex(of: tagView),
idx < groupList.count else { return }
let key = groupList[idx].group_key
viewModel.toggleGroupKey(key)
print("📋 selectedGroupKeys: \(viewModel.selectedGroupKeys)")
}
}
#if !targetEnvironment(simulator)
// MARK: - AMapSearchDelegate
extension CreateScheduleVC: AMapSearchDelegate {
func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {
guard let path = response.route?.paths?.first as? AMapPath else { return }
var coords: [CLLocationCoordinate2D] = []
for step in path.steps {
guard let polylineStr = step.polyline else { continue }
for point in polylineStr.components(separatedBy: ";") {
let latLon = point.components(separatedBy: ",")
if latLon.count == 2, let lon = Double(latLon[0]), let lat = Double(latLon[1]) {
coords.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
}
}
guard coords.count > 1 else { return }
var mutableCoords = coords
if let polyline = MAPolyline(coordinates: &mutableCoords, count: UInt(coords.count)) {
rootView.mapView.add(polyline)
routeOverlays.append(polyline)
}
}
func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
print("Route error: \(error.localizedDescription)")
}
}
#endif

View File

@ -0,0 +1,114 @@
//
// CreateScheduleVM.swift
// QuickLocation
//
// Created by 八条 on 2026/6/24.
//
import RxSwift
import RxCocoa
import RxDataSources
// MARK: - 行程点编辑模型
struct SchedulePointItem: IdentifiableType, Equatable {
let identity: String = UUID().uuidString
var locationName: String = ""
var address: String = ""
var latitude: Double = 0
var longitude: Double = 0
var province: String = ""
var city: String = ""
var district: String = ""
var street: String = ""
var country: String = ""
var formatted_address: String = ""
var expectedTime: Date?
var remark: String = ""
}
typealias SchedulePointSection = SectionModel<String, SchedulePointItem>
class CreateScheduleVM {
let disposeBag = DisposeBag()
// MARK: - Input
let addPointTapped = PublishSubject<Void>()
let deletePointAt = PublishSubject<Int>()
let updatePoint = PublishSubject<(index: Int, item: SchedulePointItem)>()
let selectedDate = BehaviorRelay<Date>(value: Date())
var selectedGroupKeys: [String] = []
/// 切换圈子选中状态(已选则删除,未选则添加)
func toggleGroupKey(_ key: String) {
if let idx = selectedGroupKeys.firstIndex(of: key) {
selectedGroupKeys.remove(at: idx)
} else {
selectedGroupKeys.append(key)
}
}
/// 删除指定圈子 key
func removeGroupKey(_ key: String) {
selectedGroupKeys.removeAll { $0 == key }
}
// MARK: - Output
let pointsRelay: BehaviorRelay<[SchedulePointItem]>
let dateString: Observable<String>
init() {
pointsRelay = BehaviorRelay<[SchedulePointItem]>(value: [
SchedulePointItem()
])
dateString = selectedDate
.map {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy年MM月dd日"
return fmt.string(from: $0)
}
// 添加行程点
addPointTapped
.withLatestFrom(pointsRelay)
.map { list in
var new = list
new.append(SchedulePointItem())
return new
}
.bind(to: pointsRelay)
.disposed(by: disposeBag)
// 删除行程点
deletePointAt
.withLatestFrom(pointsRelay) { ($1, $0) }
.subscribe(onNext: { list, idx in
guard list.count > 1, idx < list.count else { return }
var new = list
new.remove(at: idx)
self.pointsRelay.accept(new)
})
.disposed(by: disposeBag)
// 更新某个行程点
updatePoint
.withLatestFrom(pointsRelay) { ($1, $0) }
.subscribe(onNext: { list, update in
guard update.index < list.count else { return }
var new = list
new[update.index] = update.item
self.pointsRelay.accept(new)
})
.disposed(by: disposeBag)
}
/// 从 LocationPicker 回调更新某个点的位置
func updatePointLocation(index: Int, name: String, address: String) {
var list = pointsRelay.value
guard index < list.count else { return }
list[index].locationName = name
list[index].address = address
pointsRelay.accept(list)
}
}

View File

@ -31,18 +31,12 @@ class CreateScheduleView: UIView {
AppRouter.shared.popOrDismiss()
}).disposed(by: disposeBag)
// tableView 到达顶部继续下拉时,改由 PopView 的 pan 手势接管
// scrollView 到达顶部后,由 pan 手势接管 PopView 滑动
createSchedulePopView.scrollView.rx.contentOffset
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] offset in
guard let self = self else { return }
if self.isSubCanScroll {
if offset.y <= 0 {
self.isSubCanScroll = false
self.createSchedulePopView.scrollView.setContentOffset(.zero, animated: false)
}
} else if offset.y != 0 {
self.createSchedulePopView.scrollView.setContentOffset(.zero, animated: false)
}
guard let self = self, self.isSubCanScroll, offset.y <= 0 else { return }
self.createSchedulePopView.scrollView.setContentOffset(.zero, animated: false)
})
.disposed(by: disposeBag)
}
@ -110,10 +104,10 @@ class CreateScheduleView: UIView {
let newTop = panStartTop + pan.translation(in: self).y
if isSubCanScroll {
let tableViewOffset = self.createSchedulePopView.scrollView.contentOffset.y
if tableViewOffset > 0, newTop >= popUpLimit {
return
}
let scrollOffset = self.createSchedulePopView.scrollView.contentOffset.y
// 内容未到顶部时,不干涉 scrollView 的滑动
if scrollOffset > 0 { return }
// 到顶部后切为 view 拖拽
isSubCanScroll = false
panStartTop = createSchedulePopView.frame.minY
}
@ -132,15 +126,16 @@ class CreateScheduleView: UIView {
}
topConstraint.constant = target
// 非最大化时禁用 scollView 滚动
let atTop = target == self.popUpLimit
createSchedulePopView.scrollView.isScrollEnabled = atTop
if !atTop {
createSchedulePopView.scrollView.setContentOffset(.zero, animated: false)
}
UIView.animate(withDuration: 0.2, delay: 0,
options: [.curveEaseInOut, .allowUserInteraction]) {
self.layoutIfNeeded()
} completion: { _ in
let atTop = target == self.popUpLimit
self.isSubCanScroll = atTop
if !atTop {
self.createSchedulePopView.scrollView.contentOffset.y = 0
}
}
default:
@ -154,6 +149,7 @@ class CreateScheduleView: UIView {
isLimitsSet = true
popDownLimit = kScreenHeight / 3 * 2
popUpLimit = navBarView.frame.maxY
createSchedulePopView.scrollView.isScrollEnabled = false
}
}
@ -187,7 +183,7 @@ class CreateScheduleView: UIView {
}()
#if !targetEnvironment(simulator)
lazy var mapView: MAMapView = {
lazy var mapView: MAMapView! = {
let mv = MAMapView()
mv.zoomLevel = 14
mv.showsUserLocation = false
@ -197,6 +193,15 @@ class CreateScheduleView: UIView {
}()
#endif
#if !targetEnvironment(simulator)
func cleanupMap() {
mapView?.delegate = nil
mapView?.removeFromSuperview()
mapView = nil
}
#endif
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
@ -210,6 +215,27 @@ class CreateScheduleView: UIView {
}
// MARK: - UIScrollViewDelegate
extension CreateScheduleView: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// 内容已有偏移时才允许子滚动
if scrollView.contentOffset.y > 0 {
isSubCanScroll = true
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isSubCanScroll {
if scrollView.contentOffset.y <= 0 {
isSubCanScroll = false
scrollView.contentOffset.y = 0
}
} else {
scrollView.contentOffset.y = 0
}
}
}
// MARK: - UIGestureRecognizerDelegate
extension CreateScheduleView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,

View File

@ -0,0 +1,327 @@
//
// LocationPickerVC.swift
// QuickLocation
//
// Created by 八条 on 2026/6/24.
//
import UIKit
import RxSwift
import RxCocoa
import CoreLocation
import SwiftyUserDefaults
#if !targetEnvironment(simulator)
import AMapNaviKit
import AMapSearchKit
#endif
struct PickedLocation {
let name: String
let address: String
let coordinate: CLLocationCoordinate2D
var province: String = ""
var city: String = ""
var district: String = ""
var street: String = ""
var country: String = ""
var formatted_address: String = ""
}
class LocationPickerVC: BaseViewController {
override var isNavigationBarHidden: Bool { true }
var onPickedLocation: ((PickedLocation) -> Void)?
var initialLocation: PickedLocation?
fileprivate var rootView: LocationPickerView!
override func loadView() {
rootView = LocationPickerView(frame: UIScreen.main.bounds)
view = rootView
}
private var isShowPoi: Bool = false
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// 页面被 pop/dismiss 时清理地图资源
if isMovingFromParent || isBeingDismissed {
#if !targetEnvironment(simulator)
rootView.cleanupMap()
#endif
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupMap()
setupKeyboard()
setupSearch()
// 如果有初始位置,显示在底部面板
if let loc = initialLocation {
selectedLocation = loc
rootView.bottomView.isHidden = false
rootView.poiNameLab.text = loc.name
rootView.poiAddressLab.text = loc.address
if CLLocationCoordinate2DIsValid(loc.coordinate) {
rootView.mapView.setCenter(loc.coordinate, animated: false)
rootView.mapView.setZoomLevel(19, animated: false)
addLocationAnnotation(coordinate: loc.coordinate)
}
}
}
// MARK: - Keyboard
private var keyboardHeight: CGFloat = 0
private func setupKeyboard() {
NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
.subscribe(onNext: { [weak self] noti in
guard let self = self,
let frame = noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
else { return }
self.keyboardHeight = frame.height
})
.disposed(by: disposeBag)
}
// MARK: - Search
#if !targetEnvironment(simulator)
private let searchAPI = AMapSearchAPI()
private var searchPoiRequest = AMapPOIKeywordsSearchRequest()
#endif
private var selectedLocation: PickedLocation?
private var searchKeyword: String = ""
private var poiItems: [AMapPOI] = []
private var maxTableHeight: CGFloat = 300
private var currentLocation: CLLocationCoordinate2D?
private func setupSearch() {
#if !targetEnvironment(simulator)
searchAPI?.delegate = self
searchPoiRequest.city = ""
searchPoiRequest.offset = 10
if let loc = currentLocation {
searchPoiRequest.location = AMapGeoPoint.location(withLatitude: CGFloat(loc.latitude), longitude: CGFloat(loc.longitude))
}
#endif
rootView.resultTableView.delegate = self
rootView.resultTableView.dataSource = self
// 输入联想
rootView.searchField.rx.text.orEmpty
.debounce(.milliseconds(400), scheduler: MainScheduler.instance)
// .filter { $0.count >= 2 }
.subscribe(onNext: { [weak self] keyword in
self?.poiSearch(keyword: keyword)
})
.disposed(by: disposeBag)
rootView.searchField.rx.controlEvent(.editingDidBegin)
.subscribe(onNext: {
self.isShowPoi = false
})
.disposed(by: disposeBag)
rootView.searchField.rx.controlEvent(.editingDidEndOnExit)
.subscribe(onNext: { [weak self] _ in
guard let self = self, !self.poiItems.isEmpty else { return }
self.selectPOI(at: 0)
self.rootView.searchField.resignFirstResponder()
self.rootView.resultTableView.isHidden = true
})
.disposed(by: disposeBag)
// 搜索按钮 → 选中第一条联想
rootView.searchBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
guard let self = self, !self.poiItems.isEmpty else { return }
self.selectPOI(at: 0)
self.rootView.searchField.resignFirstResponder()
self.rootView.resultTableView.isHidden = true
})
.disposed(by: disposeBag)
rootView.backBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
self?.dismiss(animated: true)
})
.disposed(by: disposeBag)
rootView.confirmBtn.rx.tap
.subscribe(onNext: { [weak self] _ in
guard let self = self, let loc = self.selectedLocation else { return }
self.onPickedLocation?(loc)
self.dismiss(animated: true)
})
.disposed(by: disposeBag)
}
private func poiSearch(keyword: String) {
searchKeyword = keyword
#if !targetEnvironment(simulator)
searchPoiRequest.keywords = keyword
searchAPI?.aMapPOIKeywordsSearch(searchPoiRequest)
#endif
}
private func selectPOI(at index: Int) {
guard index < poiItems.count else { return }
selectLocation(poi: poiItems[index])
}
private func selectLocation(poi: AMapPOI) {
let coord = CLLocationCoordinate2D(latitude: CGFloat(poi.location.latitude), longitude: CGFloat(poi.location.longitude))
guard CLLocationCoordinate2DIsValid(coord) else { return }
isShowPoi = true
selectedLocation = PickedLocation(
name: poi.name ?? "",
address: poi.address ?? "",
coordinate: coord,
province: poi.province ?? "",
city: poi.city ?? "",
district: poi.district ?? "",
formatted_address: poi.address ?? ""
)
rootView.resultTableView.isHidden = true
rootView.bottomView.isHidden = false
rootView.poiNameLab.text = poi.name
rootView.poiAddressLab.text = poi.address
rootView.mapView.setCenter(coord, animated: true)
rootView.mapView.setZoomLevel(19, animated: true)
addLocationAnnotation(coordinate: coord)
}
private func updateTableHeight(itemCount: Int) {
let contentH = CGFloat(itemCount) * 50
let searchBarBottom = kStatusBarHeight + 8 + 44 + 10
let bottomOffset: CGFloat = keyboardHeight > 0 ? keyboardHeight : 200
let available = kScreenHeight - searchBarBottom - bottomOffset - 10
maxTableHeight = max(80, available)
let h = min(contentH, maxTableHeight)
rootView.resultTableView.layoutChain.height(h)
}
// MARK: - Map
private func setupMap() {
#if !targetEnvironment(simulator)
rootView.mapView.delegate = self
rootView.mapView.showsUserLocation = false
if let lat = Defaults[\.currentLatitude], let lon = Defaults[\.currentLongitude] {
let coord = CLLocationCoordinate2D(latitude: lat, longitude: lon)
if CLLocationCoordinate2DIsValid(coord) {
currentLocation = coord
rootView.mapView.setCenter(coord, animated: false)
rootView.mapView.setZoomLevel(18, animated: false)
}
}
#endif
}
private func addLocationAnnotation(coordinate: CLLocationCoordinate2D) {
#if !targetEnvironment(simulator)
for ann in rootView.mapView.annotations?.compactMap({ $0 as? MAPointAnnotation }) ?? [] {
rootView.mapView.removeAnnotation(ann)
}
let ann = MAPointAnnotation()
ann.coordinate = coordinate
rootView.mapView.addAnnotation(ann)
#endif
}
}
#if !targetEnvironment(simulator)
// MARK: - AMapSearchDelegate
extension LocationPickerVC: AMapSearchDelegate {
func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
// POI ID 搜索(来自地图点击)直接选中
if request is AMapPOIIDSearchRequest, let poi = response.pois?.first {
selectLocation(poi: poi)
return
}
// 关键字搜索
guard response.pois.count > 0, isShowPoi == false else { return }
poiItems = response.pois
rootView.resultTableView.isHidden = false
rootView.resultTableView.reloadData()
updateTableHeight(itemCount: poiItems.count)
}
func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
guard let regeo = response.regeocode else { return }
let address = regeo.formattedAddress ?? ""
selectedLocation = PickedLocation(
name: rootView.poiNameLab.text ?? "",
address: address,
coordinate: selectedLocation?.coordinate ?? kCLLocationCoordinate2DInvalid
)
rootView.poiAddressLab.text = address
}
func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
print("AMapSearch error: \(error.localizedDescription)")
}
}
// MARK: - MAMapViewDelegate
extension LocationPickerVC: MAMapViewDelegate {
func mapView(_ mapView: MAMapView!, didTouchPois pois: [Any]!) {
guard let touchPoi = pois?.first as? MATouchPoi, let uid = touchPoi.uid, !uid.isEmpty else { return }
let request = AMapPOIIDSearchRequest()
request.uid = uid
searchAPI?.aMapPOIIDSearch(request)
}
func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
if annotation is MAUserLocation { return nil }
guard annotation is MAPointAnnotation else { return nil }
let identifier = "LocationPin"
var view = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if view == nil {
view = MAAnnotationView(annotation: annotation, reuseIdentifier: identifier)
} else {
view?.annotation = annotation
}
view?.image = UIImage(named: "Schedule/location")
view?.centerOffset = CGPoint(x: 0, y: -30)
return view
}
}
// MARK: - UITableViewDataSource / Delegate
extension LocationPickerVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
poiItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
let poi = poiItems[indexPath.row]
let name = poi.name ?? ""
if !searchKeyword.isEmpty, let range = name.lowercased().range(of: searchKeyword.lowercased()) {
let attr = NSMutableAttributedString(string: name)
attr.addAttribute(.foregroundColor, value: UIColor(hexStr: "#16B3FF"), range: NSRange(range, in: name))
cell.textLabel?.attributedText = attr
} else {
cell.textLabel?.text = name
}
cell.textLabel?.font = .systemFont(ofSize: 14)
cell.detailTextLabel?.text = poi.address
cell.detailTextLabel?.font = .systemFont(ofSize: 12)
cell.detailTextLabel?.textColor = .gray
let arrow = UIImageView(image: UIImage(named: "Schedule/arrow"))
arrow.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
cell.accessoryView = arrow
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
rootView.searchField.resignFirstResponder()
selectPOI(at: indexPath.row)
rootView.searchField.text = poiItems[indexPath.row].name
}
}
#endif

View File

@ -0,0 +1,191 @@
//
// LocationPickerView.swift
// QuickLocation
//
// Created by 八条 on 2026/6/24.
//
import UIKit
import RxSwift
import RxCocoa
#if !targetEnvironment(simulator)
import AMapNaviKit
#endif
class LocationPickerView: UIView {
var disposeBag = DisposeBag()
private func setupUI() {
#if !targetEnvironment(simulator)
addSubview(mapView)
#endif
addSubview(topBgView)
topBgView.addSubview(backBtn)
topBgView.addSubview(searchField)
topBgView.addSubview(searchBtn)
addSubview(resultTableView)
addSubview(bottomView)
bottomView.addSubview(poiNameLab)
bottomView.addSubview(poiAddressLab)
bottomView.addSubview(confirmBtn)
mapView.layoutChain
.edges()
topBgView.layoutChain
.top(kStatusBarHeight + 8)
.edgesHorzontal(15)
.height(44)
backBtn.layoutChain
.left().centerY()
.width(36).height(36)
searchField.layoutChain
.leftToRightOfView(backBtn, offset: 8)
.centerY()
.right(60)
.height(36)
searchBtn.layoutChain
.right(2).centerY()
.width(80).height(36)
resultTableView.layoutChain
.topToBottomOfView(topBgView, offset: 10)
.edgesHorzontal(15)
bottomView.layoutChain
.edgesHorzontal()
.bottom()
.height(160)
poiNameLab.layoutChain
.top(16).left(16).right(16)
poiAddressLab.layoutChain
.topToBottomOfView(poiNameLab, offset: 8)
.left(16).right(16)
confirmBtn.layoutChain
.edgesHorzontal(30)
.height(44)
.bottom(kSafeBottomMargin + 16)
}
// MARK: - Views
#if !targetEnvironment(simulator)
lazy var mapView: MAMapView! = {
let mv = MAMapView()
mv.zoomLevel = 18
mv.showsUserLocation = false
mv.showsCompass = false
return mv
}()
#endif
lazy var topBgView: UIView = {
let v = UIView()
v.backgroundColor = .white
v.cornerRadius = 22
v.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor
v.layer.shadowOffset = .zero
v.layer.shadowRadius = 6
v.layer.shadowOpacity = 1
return v
}()
lazy var backBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "Common/back"), for: .normal)
btn.extendEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
return btn
}()
lazy var searchField: UITextField = {
let tf = UITextField()
tf.placeholder = "搜索地点、公园、商圈、道路"
tf.font = .systemFont(ofSize: 14)
tf.clearButtonMode = .whileEditing
tf.returnKeyType = .search
return tf
}()
lazy var searchBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("搜索", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
btn.setBackgroundImage(UIImage(named: "Common/button_bg_2"), for: .normal)
btn.cornerRadius = 18
return btn
}()
lazy var resultTableView: UITableView = {
let tv = UITableView(frame: .zero, style: .plain)
tv.backgroundColor = .white
tv.isHidden = true
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tv.estimatedRowHeight = 60
tv.cornerRadius = 10
return tv
}()
lazy var bottomView: UIView = {
let v = UIView()
v.backgroundColor = .white
v.isHidden = true
v.layer.cornerRadius = 16
v.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
v.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor
v.layer.shadowOffset = CGSize(width: 0, height: -2)
v.layer.shadowRadius = 10
v.layer.shadowOpacity = 1
return v
}()
lazy var poiNameLab: UILabel = {
let l = UILabel()
l.font = .systemFont(ofSize: 16, weight: .semibold)
l.textColor = UIColor(hexStr: "#333333")
return l
}()
lazy var poiAddressLab: UILabel = {
let l = UILabel()
l.font = .systemFont(ofSize: 13)
l.textColor = UIColor(hexStr: "#999999")
l.numberOfLines = 2
return l
}()
lazy var confirmBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("确定位置", for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
btn.setBackgroundImage(UIImage(named: "Common/button_bg_2"), for: .normal)
btn.cornerRadius = 22
return btn
}()
#if !targetEnvironment(simulator)
func cleanupMap() {
mapView?.delegate = nil
mapView?.removeFromSuperview()
mapView = nil
}
#endif
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}