修改NavigationController中backbutton

本文详细介绍了在iOS开发中如何在父ViewController中设置返回按钮,并提供了两种方法:使用UIBarButtonItem和通过设置按钮的动作和目标。同时展示了如何通过navigationController进行页面间的跳转。
父viewController中如下设置:
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];
    backbutton.title = @"返回列表";
    self.navigationItem.backBarButtonItem = backbutton;

    [backbutton release];


----------------------------------------------------------------

或者在界面中添加了按钮之后,重新定义按钮的方法

    [self.backButton setAction:@selector(OnClick_btnBack:)];

    [self.backButton setTarget:self];

-(IBAction)OnClick_btnBack:(id)sender  {

    [self.navigationController popViewControllerAnimated:YES];

    //[self.navigationController pushViewController:self.navigationController.parentViewController animated:YES];

}


import UIKit import SnapKit // MARK: - DeviceListNewViewController class DeviceListNewViewController: SurveillanceCommonTableController { // MARK: - 属性 private lazy var headerView: DeviceListHeaderView = { let view = DeviceListHeaderView() // 绑定事件回调 view.onBackTap = { [weak self] in self?.onBackTapped() } view.onLocationTap = { [weak self] in self?.onLocationTapped() } view.onSearchTap = { [weak self] in self?.onSearchTapped() } return view }() // Multi-Screen 按钮(保留在下方 section 中) private lazy var multiScreenButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("▣", for: .normal) btn.setTitleColor(.blue, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 20) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onMultiScreenTapped), for: .touchUpInside) return btn }() // MARK: - 生命周期 override func viewDidLoad() { super.viewDidLoad() self.tableView.contentInsetAdjustmentBehavior = .never reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } // MARK: - 设置子视图 override func tpbSetupSubviews() { super.tpbSetupSubviews() view.addSubview(headerView) // 只需添加一次 } // MARK: - 布局约束 override func tpbMakeConstraint() { // 不调用 super 防止干扰布局 // super.tpbMakeConstraint() headerView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide.snp.top) make.leading.trailing.equalToSuperview() make.height.equalTo(50) } tableView.snp.remakeConstraints { make in make.top.equalTo(headerView.snp.bottom).offset(10) make.leading.trailing.bottom.equalToSuperview() } } // MARK: - 创建 “Multi-Screen” 行(保持不变) private func createAllDevicesRowView() -> UIView { let container = UIView() container.backgroundColor = UIColor(white: 0.95, alpha: 1.0) container.layer.cornerRadius = 8 container.clipsToBounds = true let stackView = UIStackView(arrangedSubviews: [multiScreenButton]) stackView.axis = .horizontal stackView.distribution = .equalCentering stackView.alignment = .center stackView.spacing = 16 container.addSubview(stackView) stackView.snp.makeConstraints { make in make.edges.equalTo(container).inset(16) } return container } // 占位内容视图 private func createPlaceholderDeviceListView() -> UIView { let view = UIView() view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) view.layer.cornerRadius = 12 view.clipsToBounds = true let label = UILabel() label.text = "正在显示所有设备..." label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = UIColor.gray label.textAlignment = .center view.addSubview(label) label.snp.makeConstraints { make in make.center.equalTo(view) } return view } // 刷新设备列表 Section private func refreshDeviceListSection() { let cellModel = TPBBaseTableCellModel.customContent(with: createPlaceholderDeviceListView()) cellModel.height = TPBTableElementHeight.customHeight(200) let section = TPBTableSectionModel() section.cellModelArray = [cellModel] if sectionArray.count > 1 { sectionArray[1] = section } else { sectionArray.append(section) } } // 加载数据 private func reloadData() { var tempSectionArray = [TPBTableSectionModel]() let section0 = TPBTableSectionModel() var cellModels = [TPBBaseTableCellModel]() // 设备总数 let deviceCountView = createDeviceCountView() let deviceCountCellModel = TPBBaseTableCellModel.customContent(with: deviceCountView) deviceCountCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(deviceCountCellModel) // 存储空间 let storageView = createStorageUsageView() let storageCellModel = TPBBaseTableCellModel.customContent(with: storageView) storageCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(storageCellModel) // Multi-Screen 按钮行 let devicesRowView = createAllDevicesRowView() let devicesRowCellModel = TPBBaseTableCellModel.customContent(with: devicesRowView) devicesRowCellModel.height = TPBTableElementHeight.customHeight(72) cellModels.append(devicesRowCellModel) section0.cellModelArray = cellModels tempSectionArray.append(section0) // 更新设备列表区域 refreshDeviceListSection() sectionArray = tempSectionArray + Array(sectionArray.dropFirst(max(0, sectionArray.count - 1))) tableView.reloadData() } // 自定义 View 构建函数 private func createDeviceCountView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "设备总数:32 台" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .red view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } private func createStorageUsageView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "已用存储:1.2 TB / 5 TB" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .tpbTextPrimary view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } // MARK: - Action 回调 @objc private func onBackTapped() { navigationController?.popViewController(animated: true) } @objc private func onLocationTapped() { print("定位按钮点击") } @objc private func onSearchTapped() { print("搜索按钮点击") } @objc private func onMultiScreenTapped() { print("Multi-Screen 按钮被点击") } } // MARK: - DeviceListCell(保持不变) class DeviceListCell: UICollectionViewCell { private let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } private func setupUI() { backgroundColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 0.1) layer.borderColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0).cgColor layer.borderWidth = 1 layer.cornerRadius = 8 clipsToBounds = true titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) titleLabel.textColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0) titleLabel.textAlignment = .center titleLabel.numberOfLines = 1 titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.center.equalTo(contentView) make.leading.greaterThanOrEqualTo(contentView).offset(8) make.trailing.lessThanOrEqualTo(contentView).offset(-8) } } func configure(with title: String) { titleLabel.text = title } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil } } // MARK: - DeviceListHeaderView fileprivate class DeviceListHeaderView: TPBBaseView { // MARK: - 子视图 private let backButton = UIButton(type: .custom) private let locationButton = UIButton(type: .custom) private let titleLabel = UILabel() private let searchButton = UIButton(type: .custom) private let separatorLine = UIView() // MARK: - Callbacks var onBackTap: (() -> Void)? var onLocationTap: (() -> Void)? var onSearchTap: (() -> Void)? // MARK: - 初始化 override init(frame: CGRect) { super.init(frame: frame) setupUI() setupLayout() } required init?(coder: NSCoder) { super.init(coder: coder) setupUI() setupLayout() } private func setupUI() { backgroundColor = .tpbBackground // Back Button backButton.setTitle("←", for: .normal) backButton.setTitleColor(.blue, for: .normal) backButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) backButton.addTarget(self, action: #selector(onBackTapped), for: .touchUpInside) // Location Button locationButton.setTitle("📍", for: .normal) locationButton.setTitleColor(.blue, for: .normal) locationButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) locationButton.addTarget(self, action: #selector(onLocationTapped), for: .touchUpInside) // Title Label titleLabel.text = "设备列表" titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium) titleLabel.textColor = .red titleLabel.textAlignment = .center // Search Button searchButton.setTitle("🔍", for: .normal) searchButton.setTitleColor(.blue, for: .normal) searchButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) searchButton.addTarget(self, action: #selector(onSearchTapped), for: .touchUpInside) // Separator Line separatorLine.backgroundColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 0.3) // 添加子视图 addSubviews(backButton, locationButton, titleLabel, searchButton, separatorLine) } private func setupLayout() { backButton.snp.makeConstraints { make in make.leading.equalToSuperview().offset(16) make.centerY.equalToSuperview() make.width.greaterThanOrEqualTo(30) } locationButton.snp.makeConstraints { make in make.leading.equalTo(backButton.snp.trailing).offset(8) make.centerY.equalTo(backButton) make.size.equalTo(30) } titleLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.centerY.equalTo(backButton) } searchButton.snp.makeConstraints { make in make.trailing.equalToSuperview().offset(-16) make.centerY.equalTo(backButton) make.width.greaterThanOrEqualTo(30) } separatorLine.snp.makeConstraints { make in make.height.equalTo(1 / UIScreen.main.scale) make.leading.trailing.bottom.equalToSuperview() } } // MARK: - Actions @objc private func onBackTapped() { onBackTap?() } @objc private func onLocationTapped() { onLocationTap?() } @objc private func onSearchTapped() { onSearchTap?() } } 这对吗?
12-04
请按照上述那样的方式给我同样修改,要求只修改HeadervIew部分,其余先不变,也同样继承TPBBaseview,先自定义再继承使用的方式 import UIKit import SnapKit // MARK: - DeviceListNewViewController class DeviceListNewViewController: SurveillanceCommonTableController { // 吸顶头部 private lazy var stickyHeader: UIView = { let header = UIView() header.backgroundColor = .tpbBackground return header }() private lazy var backButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("←", for: .normal) btn.setTitleColor(UIColor.blue, for: .normal) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onBackTapped), for: .touchUpInside) return btn }() private lazy var locationButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("📍", for: .normal) btn.setTitleColor(UIColor.blue, for: .normal) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onLocationTapped), for: .touchUpInside) return btn }() private lazy var titleLabel: UILabel = { let label = UILabel() label.text = "设备列表" label.font = UIFont.systemFont(ofSize: 18, weight: .medium) label.textColor = .red label.textAlignment = .center return label }() private lazy var searchButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("🔍", for: .normal) btn.setTitleColor(UIColor.blue, for: .normal) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onSearchTapped), for: .touchUpInside) return btn }() private lazy var separatorLine: UIView = { let line = UIView() line.backgroundColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 0.3) return line }() // Multi-Screen 按钮 private lazy var multiScreenButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("▣", for: .normal) btn.setTitleColor(.blue, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 20) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onMultiScreenTapped), for: .touchUpInside) return btn }() // MARK: - 生命周期 override func viewDidLoad() { super.viewDidLoad() self.tableView.contentInsetAdjustmentBehavior = .never reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } override func tpbSetupSubviews() { super.tpbSetupSubviews() // 添加吸顶栏 view.addSubview(stickyHeader) stickyHeader.addSubview(backButton) stickyHeader.addSubview(locationButton) stickyHeader.addSubview(titleLabel) stickyHeader.addSubview(searchButton) stickyHeader.addSubview(separatorLine) } override func tpbMakeConstraint() { stickyHeader.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide.snp.top) make.leading.trailing.equalToSuperview() make.height.equalTo(50) } backButton.snp.remakeConstraints { make in make.leading.equalTo(stickyHeader).offset(16) make.centerY.equalTo(stickyHeader) make.width.greaterThanOrEqualTo(30) } locationButton.snp.remakeConstraints { make in make.leading.equalTo(backButton.snp.trailing).offset(8) make.centerY.equalTo(backButton) make.size.equalTo(30) } titleLabel.snp.remakeConstraints { make in make.centerX.equalToSuperview() make.centerY.equalTo(backButton) } searchButton.snp.remakeConstraints { make in make.trailing.equalTo(stickyHeader).offset(-16) make.centerY.equalTo(backButton) make.width.greaterThanOrEqualTo(30) } separatorLine.snp.makeConstraints { make in make.height.equalTo(1 / UIScreen.main.scale) make.leading.trailing.bottom.equalToSuperview() } tableView.snp.remakeConstraints { make in make.top.equalTo(stickyHeader.snp.bottom).offset(10) make.leading.trailing.bottom.equalToSuperview() } } // MARK: - 创建 “Multi-Screen” 行 private func createAllDevicesRowView() -> UIView { let container = UIView() container.backgroundColor = UIColor(white: 0.95, alpha: 1.0) container.layer.cornerRadius = 8 container.clipsToBounds = true // 使用 UIStackView 布局文字和按钮 let stackView = UIStackView(arrangedSubviews: [ multiScreenButton]) stackView.axis = .horizontal stackView.distribution = .equalCentering stackView.alignment = .center stackView.spacing = 16 container.addSubview(stackView) stackView.snp.makeConstraints { make in make.edges.equalTo(container).inset(16) } return container } // MARK: - 刷新设备列表 Section(占位) private func refreshDeviceListSection() { let cellModel = TPBBaseTableCellModel.customContent(with: createPlaceholderDeviceListView()) cellModel.height = TPBTableElementHeight.customHeight(200) let section = TPBTableSectionModel() section.cellModelArray = [cellModel] if sectionArray.count > 1 { sectionArray[1] = section } else { sectionArray.append(section) } } // 占位内容视图(下方设备展示区) private func createPlaceholderDeviceListView() -> UIView { let view = UIView() view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) view.layer.cornerRadius = 12 view.clipsToBounds = true let label = UILabel() label.text = "正在显示所有设备..." label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = UIColor.gray label.textAlignment = .center view.addSubview(label) label.snp.makeConstraints { make in make.center.equalTo(view) } return view } // MARK: - 加载初始数据 private func reloadData() { var tempSectionArray = [TPBTableSectionModel]() // Section 0: 卡片信息 let section0 = TPBTableSectionModel() var cellModels = [TPBBaseTableCellModel]() // 设备总数视图 let deviceCountView = createDeviceCountView() let deviceCountCellModel = TPBBaseTableCellModel.customContent(with: deviceCountView) deviceCountCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(deviceCountCellModel) // 存储空间视图 let storageView = createStorageUsageView() let storageCellModel = TPBBaseTableCellModel.customContent(with: storageView) storageCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(storageCellModel) // 所有设备 + 多屏查看按钮行 let devicesRowView = createAllDevicesRowView() let devicesRowCellModel = TPBBaseTableCellModel.customContent(with: devicesRowView) devicesRowCellModel.height = TPBTableElementHeight.customHeight(72) cellModels.append(devicesRowCellModel) section0.cellModelArray = cellModels tempSectionArray.append(section0) // 初始化设备列表区域(占位) refreshDeviceListSection() // 合并 sections sectionArray = tempSectionArray + Array(sectionArray.dropFirst(max(0, sectionArray.count - 1))) tableView.reloadData() } // MARK: - 自定义 View 构建函数 private func createDeviceCountView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "设备总数:32 台" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .red label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } private func createStorageUsageView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "已用存储:1.2 TB / 5 TB" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .tpbTextPrimary label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } // MARK: - Action 回调 @objc private func onBackTapped() { navigationController?.popViewController(animated: true) } @objc private func onLocationTapped() { print("定位按钮点击") } @objc private func onSearchTapped() { print("搜索按钮点击") } @objc private func onMultiScreenTapped() { print("Multi-Screen 按钮被点击") // 可弹出多屏监控页面或跳转 } } // MARK: - DeviceListCell(保留原类用于其他场景或过渡) class DeviceListCell: UICollectionViewCell { private let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } private func setupUI() { backgroundColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 0.1) layer.borderColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0).cgColor layer.borderWidth = 1 layer.cornerRadius = 8 clipsToBounds = true titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) titleLabel.textColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0) titleLabel.textAlignment = .center titleLabel.numberOfLines = 1 titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.center.equalTo(contentView) make.leading.greaterThanOrEqualTo(contentView).offset(8) make.trailing.lessThanOrEqualTo(contentView).offset(-8) } } func configure(with title: String) { titleLabel.text = title } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil } }
12-04
我再说一遍,下面是示例代码,请你仿照这个的写法好好检查,重新生成所有代码。 示例代码: import UIKit class EditOrganizationMainViewController: SurveillanceCommonTableController { // MARK: - 属性 private lazy var orgHeaderView: EditOrganizationOrgHeaderView = { let view = EditOrganizationOrgHeaderView() return view }() private lazy var appContext = { TPAppContextFactory.shared() }() // 组织信息 private var orgInfo = TPSSVMSOrganizationInfo() private var userManagementPermission: Bool{ get{ #if APP_VIGI if !appContext.currentRolePermission.userManagement { return false } return true #else if orgInfo.vmsOrgType == .omadaSurOnlyCloud{ if !appContext.currentRolePermission.userManagement { return false } } else { if appContext.accountInfo.centralPermission.centralUsers == .block { return false } } return true #endif } } // 必须使用该初始化方式 convenience init(orgInfo: TPSSVMSOrganizationInfo) { self.init() self.orgInfo = orgInfo } deinit { print("EditOrganizationMainViewController deinit") } // MARK: - View override func tpbSetupSubviews() { super.tpbSetupSubviews() view.addSubview(orgHeaderView) } override func tpbMakeConstraint() { // 暂不执行super不然会显示不了title // super.tpbMakeConstraint() orgHeaderView.snp.makeConstraints { make in make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) } tableView.snp.remakeConstraints { make in make.top.equalTo(orgHeaderView.snp.bottom) make.leading.trailing.equalTo(view.safeAreaLayoutGuide) make.bottom.equalTo(view) } } override func viewDidLoad() { super.viewDidLoad() requestRolePermission() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // TODO: 接入Omada Central之后需要判定是否隐藏 navigationController?.setNavigationBarHidden(true, animated: false) // 获取基本信息 getOrgDetailInfo() reloadView() } private func reloadView() { orgHeaderView.updateWith(orgName: orgInfo.vmsName, orgCategory: orgInfo.vmsOrgCategory) { [weak self] in if let org = self?.orgInfo { let vc = EditOrganizationSettingsViewController(orgInfo: org) self?.navigationController?.pushViewController(vc, animated: true) } } reloadData() } // MARK: - dateModel private func reloadData() { var tempSectionArray = [TPBTableSectionModel]() // section0 // let section0 = TPBTableSectionModel() // var section0CellModelArray = [TPBBaseTableCellModel]() // // // // section0.cellModelArray = section0CellModelArray // tempSectionArray.append(section0) #if APP_OMADA // section1 let section1 = TPBTableSectionModel() var section1CellModelArray = [TPBBaseTableCellModel]() if orgInfo.networkSelect { let omadaNetworkCellModel = TPBBaseTableCellModel.titleSubtitle(withIcon: TPImageLiteral("central_network"), title: LocalizedString(key: addOrganizationOmadaNetwork), subtitle: nil, value: orgInfo.networkVersion, infoItemArray: nil, action: nil, showIndicator: false) section1CellModelArray.append(omadaNetworkCellModel) } if orgInfo.surveillanceSelect { let omadaGuardCellModel = TPBBaseTableCellModel.titleSubtitle(withIcon: TPImageLiteral("central_surveillance"), title: LocalizedString(key: shareSocialPlatformWebDetail), subtitle: nil, value: orgInfo.surveillanceVersion, infoItemArray: nil, action: nil, showIndicator: false) section1CellModelArray.append(omadaGuardCellModel) } section1.cellModelArray = section1CellModelArray section1.headerTitle = LocalizedString(key: editOrganizationApplication) tempSectionArray.append(section1) #endif // section2 let section2 = TPBTableSectionModel() var section2CellModelArray = [TPBBaseTableCellModel]() if currentOrgIsGuardOnly || TPSSAppContext.shared.accountInfo.centralPermission.centralGlobalSetting != .block { let generalSettingCellModel = TPBBaseTableCellModel.titleSubtitle(withIcon: nil, title: LocalizedString(key: configTitle), subtitle: nil, value: nil, infoItemArray: nil, action: { [weak self] _, _ in if let org = self?.orgInfo { let vc = EditOrganizationSettingsViewController(orgInfo: org) self?.navigationController?.pushViewController(vc, animated: true) } }, showIndicator: true) section2CellModelArray.append(generalSettingCellModel) } let siteManagementCellModel = TPBBaseTableCellModel.titleSubtitle(withIcon: nil, title: LocalizedString(key: editOrganizationSiteManagement), subtitle: nil, value: nil, infoItemArray: nil, action: { [weak self] _, _ in let vc = OmadaSiteManagementListViewController() self?.navigationController?.pushViewController(vc, animated: true) }, showIndicator: true) section2CellModelArray.append(siteManagementCellModel) let userManagementCellModel = TPBBaseTableCellModel.titleSubtitle(withIcon: nil, title: LocalizedString(key: editOrganizationUserManagement), subtitle: nil, value: nil, infoItemArray: nil, action: { [weak self] _, _ in self?.clickUserManagement() }, showIndicator: true) section2CellModelArray.append(userManagementCellModel) section2.cellModelArray = section2CellModelArray tempSectionArray.append(section2) // section3 let section3 = TPBTableSectionModel() var section3CellModelArray = [TPBBaseTableCellModel]() #if APP_VIGI if let hasCloudVMSOrganization = UserDefaults.standard.object(forKey: kHasCloudVMSOrganization) as? Bool { if TPSSAppContext.shared.isSupportCreateOrg || hasCloudVMSOrganization { let createOrgCellModel = TPBBaseTableCellModel.action(withIcon: nil, title: LocalizedString(key: createNewOrganization), action: { _, _ in let vc = AddOrganizationCreateOrgViewController() if let rootVC = UIApplication.shared.keyWindow?.rootViewController as? MainModuleTabBarController { rootVC.presentFullScreenViewController(vc) } }, actionEnabled: true, titleColor: .tpbPrimary) section3CellModelArray.append(createOrgCellModel) } } #else if appContext.accountInfo.createCuardServiceDisable != 1 { } #endif #if APP_VIGI let title = appContext.accountInfo.roleName == DefaultRoleName.owner.rawValue ? LocalizedString(key: editOrganizationDeleteOrganization) : LocalizedString(key: editOrganizationLeaveOrganization) #else let title = orgInfo.role == .owner ? LocalizedString(key: editOrganizationDeleteOrganization) : LocalizedString(key: editOrganizationLeaveOrganization) #endif let deleteCellModel = TPBBaseTableCellModel.action(withIcon: nil, title: title, action: { [weak self] _, _ in self?.showDeleteAlert() }, actionEnabled: true, titleColor: .tpbRed) section3CellModelArray.append(deleteCellModel) section3.cellModelArray = section3CellModelArray tempSectionArray.append(section3) sectionArray = tempSectionArray } // MARK: - 点击事件 @objc private func clickBack() { dismiss(animated: true) } private func showDeleteAlert() { #if APP_VIGI // 如果是owner则需要获取VmsStatistics,根据返回结果决定弹窗表现;如果是user则直接弹窗 if appContext.accountInfo.roleName == DefaultRoleName.owner.rawValue { RequestAsyncHandler.default.perform({ () -> TPSSCode in ToastView.showLoadingToast(cirleWithMessage: nil) return appContext.requestGetVmsStatistics() }, callback: { [weak self] result in guard let self = self else { return } ToastView.dismissLoadingToast() if result.isSuccess() { // 根据返回结果决定弹窗表现 self.showVMSOwnerDeleteAlert() } else { var errorMessage = result.error() if result.notification?.parameter0() == TPSS_EC_TIMEOUT || result.notification?.parameter0() == TPSS_EC_NET_ERROR || errorMessage == "" { errorMessage = LocalizedString(key: deviceSettingWifiNvrGetStatusFail) } ToastView.showTopWarningWithLeftIconToast(title: errorMessage, type: .info, existTime: 2) } }) } else { tpbShowAlert(withTitle: LocalizedString(key: editOrganizationLeaveOrganizationAlertTitle), messsage: nil, cancelText: LocalizedString(key: commonCancel), cancelCallback: nil, deleteText: LocalizedString(key: deviceSettingUpgradeLeave)) { [weak self] in self?.deleteOrg() } } #else let title = orgInfo.role == .owner ? LocalizedString(key: editOrganizationDeleteOrganizationAlertTitle) : LocalizedString(key: editOrganizationLeaveOrganizationAlertTitle) let deleteText = orgInfo.role == .owner ? LocalizedString(key: commonDelete) : LocalizedString(key: deviceSettingUpgradeLeave) tpbShowAlert(withTitle: title, messsage: nil, cancelText: LocalizedString(key: commonCancel), cancelCallback: nil, deleteText: deleteText) { [weak self] in self?.deleteOrg() } #endif } private func showVMSOwnerDeleteAlert() { if let vmsStatistics = appContext.getVmsStatistics() { let isCloudBackUp = TPSSAppContext.shared.getVMSIsSupportCloudStorage() != 0 if vmsStatistics.deviceNum == 0 { // 设备数为0 if vmsStatistics.orgManagerNum == 0 { // 用户为0 if isCloudBackUp { // 云备份开启 if vmsStatistics.hasActivePackages { showVMSOwnerDeleteUnableToDeleteAlertView() } else if vmsStatistics.hasOrgBackupVideos { showVMSOwnerDeleteCanDeleteAlertView() } else { showVMSOwnerDeleteCanDeleteAlertView() } } else { showVMSOwnerDeleteCanDeleteAlertView() } } else { showVMSOwnerDeleteCanDeleteAlertView() } } else { if isCloudBackUp { // 云备份开启 if vmsStatistics.hasActivePackages { showVMSOwnerDeleteUnableToDeleteAlertView() } else { showVMSOwnerDeleteUnableToDeleteAlertView() } } else { showVMSOwnerDeleteUnableToDeleteAlertView() } } } } // 可以删除提示 private func showVMSOwnerDeleteCanDeleteAlertView() { tpbShowAlert(withTitle: LocalizedString(key: editOrganizationVMSDeleteOrganizationTip), messsage: nil, cancelText: LocalizedString(key: commonCancel), cancelCallback: nil, deleteText: LocalizedString(key: commonDelete)) { [weak self] in self?.deleteOrg() } } // 不可以删除提示 private func showVMSOwnerDeleteUnableToDeleteAlertView() { tpbShowAlert(withTitle: LocalizedString(key: editOrganizationVMSUnabletoDeleteOrganizationTip), buttonText: LocalizedString(key: commonKnown)) } private func clickUserManagement() { if userManagementPermission { let vc = UserManagementViewController() navigationController?.pushViewController(vc, animated: true) } else { tpbShowAlertToastFailure(withTitle: TPSSAppContext.errorMsg(forLocalizedKey: IPC_EM_FINISH_REASON_PERMISSION_DENIED)) } } // MARK: - 发送请求 private func requestRolePermission(){ //适配多端修改问题 if currentOrgIsGuardOnly { appContext.requestCloudVMSRolePermission() } else { appContext.requestCentralRolePermission() } } private func getOrgDetailInfo() { RequestAsyncHandler.default.perform({ () -> TPSSCode in // 获取组织信息 #if APP_VIGI return appContext.requestVMSOrgInfo() #else return appContext.requestGetCloudOmadaOrgDetails(byVmsId: orgInfo.vmsId) #endif }, callback: { [weak self] result in guard let self = self else { return } if result.isSuccess() { let currentVMSId = appContext.currentVMSId if let org = self.appContext.getVmsInfo(byVmsId: currentVMSId) { // 为保证浅拷贝有效,此处仅修改值,而非直接用底层获取的值替换 self.orgInfo.vmsName = org.vmsName self.orgInfo.region = org.region self.orgInfo.countryCode = org.countryCode self.orgInfo.timeZone = org.timeZone self.orgInfo.networkVersion = org.networkVersion self.orgInfo.surveillanceVersion = org.surveillanceVersion self.reloadView() } else { self.orgInfo.vmsName = appContext.accountInfo.currentVmsName self.orgInfo.timeZone = appContext.accountInfo.currentVmsTimeZone self.orgInfo.countryCode = appContext.accountInfo.currentVmsCountryCode } } else { var errorMessage = result.error() if result.notification?.parameter0() == TPSS_EC_TIMEOUT || result.notification?.parameter0() == TPSS_EC_NET_ERROR || errorMessage == "" { errorMessage = LocalizedString(key: deviceSettingWifiNvrGetStatusFail) } ToastView.showTopWarningWithLeftIconToast(title: errorMessage, type: .info, existTime: 2) } }) } private func deleteOrg() { RequestAsyncHandler.default.perform({ () -> TPSSCode in ToastView.showLoadingToast(cirleWithMessage: nil) #if APP_VIGI return appContext.requestDeleteVms(byPassword: "") #else return appContext.requestForgetCloudOmadaOrg(byVmsId: orgInfo.vmsId) #endif }, callback: { [weak self] result in guard let self = self else { return } ToastView.dismissLoadingToast() if result.isSuccess() { self.appContext.initVms(.personal, organizationId: "") // 清空上一次选择的站点信息 UserDefaults.standard.deviceListSelectedType = nil FileManager.default.removeVmsSelectedSiteInfo() #if APP_VIGI // vigi需要在组织列表为空时跳帐密页,也需要登出 let getVMSOrganizationList = self.appContext.getVMSOrganizationList() let orgList = getVMSOrganizationList.filter { [weak self] info in guard let self2 = self else { return false } return info.vmsId != self2.orgInfo.vmsId } let unverifyOrgList = self.appContext.getUnverifyVMSOrganizationList() if orgList.isEmpty && unverifyOrgList.isEmpty { self.jumpToAccountLoginVC() } else { self.jumpToSelectOrganizationVC() } #else self.jumpToSelectOrganizationVC() #endif } else { var errorMessage = result.error() if result.notification?.parameter0() == TPSS_EC_TIMEOUT || result.notification?.parameter0() == TPSS_EC_NET_ERROR || errorMessage == "" { errorMessage = LocalizedString(key: deviceSettingWifiNvrGetStatusFail) } ToastView.showTopWarningWithLeftIconToast(title: errorMessage, type: .info, existTime: 2) } }) } private func jumpToSelectOrganizationVC() { let vc = AccountSelectOrganizationViewController() vc.getOrgStatusTypeFromLogin = .success vc.jumpToLastViewHandle = { //静默登出 TPAppContextFactory.shared().requestLogout() if(UIApplication.shared.isRegisteredForRemoteNotifications){ UIApplication.shared.unregisterForRemoteNotifications() } } UIApplication.shared.keyWindow?.rootViewController = BaseNavigationController(rootViewController: vc) } private func jumpToAccountLoginVC() { let destinationStoryboard = UIStoryboard(name: "AccountManager", bundle: nil) if let destinationViewController = destinationStoryboard.instantiateViewController(withIdentifier: "accountManagerLogin") as? AccountLoginViewController { //静默登出 TPAppContextFactory.shared().requestLogout() if(UIApplication.shared.isRegisteredForRemoteNotifications){ UIApplication.shared.unregisterForRemoteNotifications() } let navigationVC = BaseNavigationController(rootViewController: destinationViewController) UIApplication.shared.keyWindow?.rootViewController = navigationVC } } } // 自定义view fileprivate class EditOrganizationOrgHeaderView: TPBBaseView { // MARK: - 属性 private lazy var nameLabel: UILabel = { let label = UILabel() label.text = " " label.numberOfLines = 1 label.font = .tpr22Regular() label.textColor = .tpbTextPrimary label.textAlignment = .left label.lineBreakMode = .byTruncatingTail return label }() private lazy var orgCategoryContainerView: UIView = { let view = UIView() view.backgroundColor = .tpbPrimaryLight view.layer.cornerRadius = 3 view.layer.masksToBounds = true view.setContentHuggingPriority(.required, for: .horizontal) view.setContentCompressionResistancePriority(.required, for: .horizontal) return view }() private lazy var orgCategorylabel: UILabel = { let label = UILabel() label.text = LocalizedString(key: orgCategoryEssential) label.font = .tpr12Regular() label.textColor = .tpbPrimary label.numberOfLines = 1 label.lineBreakMode = .byTruncatingTail label.textAlignment = .left label.setContentHuggingPriority(.required, for: .horizontal) label.setContentCompressionResistancePriority(.required, for: .horizontal) return label }() // MARK: - View override func setupSubviews() { super.setupSubviews() backgroundColor = .tpbBackground addSubviews([nameLabel, orgCategoryContainerView]) orgCategoryContainerView.addSubview(orgCategorylabel) #if APP_VIGI orgCategoryContainerView.isHidden = true #endif } override func makeConstraint() { super.makeConstraint() nameLabel.snp.makeConstraints { make in make.leading.equalToSuperview().offset(20) make.top.equalToSuperview().offset(20) if orgCategoryContainerView.isHidden { make.trailing.equalToSuperview().offset(-20) } make.bottom.equalToSuperview().offset(-10) } orgCategoryContainerView.snp.makeConstraints { make in make.leading.equalTo(nameLabel.snp.trailing).offset(8) make.trailing.lessThanOrEqualToSuperview().offset(-20) make.centerY.equalTo(nameLabel) } orgCategorylabel.snp.makeConstraints { make in make.leading.equalToSuperview().offset(6) make.trailing.equalToSuperview().offset(-6) make.top.equalToSuperview().offset(2) make.bottom.equalToSuperview().offset(-2) } } // MARK: -更新函数 func updateWith(orgName: String, orgCategory: TPSSVMSOrgCategory, clickGeneralSettingsBlock: @escaping (() -> Void)) { nameLabel.text = orgName if orgCategory == .essential { orgCategorylabel.text = LocalizedString(key: orgCategoryEssential) orgCategorylabel.textColor = .tpbBlue orgCategoryContainerView.backgroundColor = .tpbBlueLight } else { orgCategorylabel.text = LocalizedString(key: deviceSettingSmartWhiteLampModeAutoWTL) orgCategorylabel.textColor = .tpbPrimary orgCategoryContainerView.backgroundColor = .tpbPrimaryLight } #if APP_VIGI #endif } } 我的代码:import UIKit import SnapKit // MARK: - DeviceListNewViewController class DeviceListNewViewController: SurveillanceCommonTableController { // MARK: - 属性 private lazy var headerView: DeviceListHeaderView = { let view = DeviceListHeaderView() // 绑定事件回调 view.onBackTap = { [weak self] in self?.onBackTapped() } view.onLocationTap = { [weak self] in self?.onLocationTapped() } view.onSearchTap = { [weak self] in self?.onSearchTapped() } return view }() // Multi-Screen 按钮(保留在下方 section 中) private lazy var multiScreenButton: UIButton = { let btn = UIButton(type: .custom) btn.setTitle("▣", for: .normal) btn.setTitleColor(.blue, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 20) btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) btn.addTarget(self, action: #selector(onMultiScreenTapped), for: .touchUpInside) return btn }() // MARK: - 生命周期 override func viewDidLoad() { super.viewDidLoad() self.tableView.contentInsetAdjustmentBehavior = .never reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } // MARK: - 设置子视图 override func tpbSetupSubviews() { super.tpbSetupSubviews() view.addSubview(headerView) // 只需添加一次 } // MARK: - 布局约束 override func tpbMakeConstraint() { // 不调用 super 防止干扰布局 // super.tpbMakeConstraint() headerView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide.snp.top) make.leading.trailing.equalToSuperview() make.height.equalTo(50) } tableView.snp.remakeConstraints { make in make.top.equalTo(headerView.snp.bottom).offset(10) make.leading.trailing.bottom.equalToSuperview() } } // MARK: - 创建 “Multi-Screen” 行(保持不变) private func createAllDevicesRowView() -> UIView { let container = UIView() container.backgroundColor = UIColor(white: 0.95, alpha: 1.0) container.layer.cornerRadius = 8 container.clipsToBounds = true let stackView = UIStackView(arrangedSubviews: [multiScreenButton]) stackView.axis = .horizontal stackView.distribution = .equalCentering stackView.alignment = .center stackView.spacing = 16 container.addSubview(stackView) stackView.snp.makeConstraints { make in make.edges.equalTo(container).inset(16) } return container } // 占位内容视图 private func createPlaceholderDeviceListView() -> UIView { let view = UIView() view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) view.layer.cornerRadius = 12 view.clipsToBounds = true let label = UILabel() label.text = "正在显示所有设备..." label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = UIColor.gray label.textAlignment = .center view.addSubview(label) label.snp.makeConstraints { make in make.center.equalTo(view) } return view } // 刷新设备列表 Section private func refreshDeviceListSection() { let cellModel = TPBBaseTableCellModel.customContent(with: createPlaceholderDeviceListView()) cellModel.height = TPBTableElementHeight.customHeight(200) let section = TPBTableSectionModel() section.cellModelArray = [cellModel] if sectionArray.count > 1 { sectionArray[1] = section } else { sectionArray.append(section) } } // 加载数据 private func reloadData() { var tempSectionArray = [TPBTableSectionModel]() let section0 = TPBTableSectionModel() var cellModels = [TPBBaseTableCellModel]() // 设备总数 let deviceCountView = createDeviceCountView() let deviceCountCellModel = TPBBaseTableCellModel.customContent(with: deviceCountView) deviceCountCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(deviceCountCellModel) // 存储空间 let storageView = createStorageUsageView() let storageCellModel = TPBBaseTableCellModel.customContent(with: storageView) storageCellModel.height = TPBTableElementHeight.customHeight(60) cellModels.append(storageCellModel) // Multi-Screen 按钮行 let devicesRowView = createAllDevicesRowView() let devicesRowCellModel = TPBBaseTableCellModel.customContent(with: devicesRowView) devicesRowCellModel.height = TPBTableElementHeight.customHeight(72) cellModels.append(devicesRowCellModel) section0.cellModelArray = cellModels tempSectionArray.append(section0) // 更新设备列表区域 refreshDeviceListSection() sectionArray = tempSectionArray + Array(sectionArray.dropFirst(max(0, sectionArray.count - 1))) tableView.reloadData() } // 自定义 View 构建函数 private func createDeviceCountView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "设备总数:32 台" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .red view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } private func createStorageUsageView() -> UIView { let view = UIView() view.backgroundColor = .clear let label = UILabel() label.text = "已用存储:1.2 TB / 5 TB" label.font = UIFont.systemFont(ofSize: 16, weight: .regular) label.textColor = .tpbTextPrimary view.addSubview(label) label.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(16) } return view } // MARK: - Action 回调 @objc private func onBackTapped() { navigationController?.popViewController(animated: true) } @objc private func onLocationTapped() { print("定位按钮点击") } @objc private func onSearchTapped() { print("搜索按钮点击") } @objc private func onMultiScreenTapped() { print("Multi-Screen 按钮被点击") } } // MARK: - DeviceListCell(保持不变) class DeviceListCell: UICollectionViewCell { private let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } private func setupUI() { backgroundColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 0.1) layer.borderColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0).cgColor layer.borderWidth = 1 layer.cornerRadius = 8 clipsToBounds = true titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) titleLabel.textColor = UIColor(red: 0.0, green: 0.4, blue: 1.0, alpha: 1.0) titleLabel.textAlignment = .center titleLabel.numberOfLines = 1 titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.center.equalTo(contentView) make.leading.greaterThanOrEqualTo(contentView).offset(8) make.trailing.lessThanOrEqualTo(contentView).offset(-8) } } func configure(with title: String) { titleLabel.text = title } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil } } // MARK: - DeviceListHeaderView fileprivate class DeviceListHeaderView: TPBBaseView { // MARK: - 子视图 private let backButton = UIButton(type: .custom) private let locationButton = UIButton(type: .custom) private let titleLabel = UILabel() private let searchButton = UIButton(type: .custom) private let separatorLine = UIView() // MARK: - 回调闭包 var onBackTap: (() -> Void)? var onLocationTap: (() -> Void)? var onSearchTap: (() -> Void)? // MARK: - 设置子视图 override func setupSubviews() { super.setupSubviews() backgroundColor = .tpbBackground // Back Button backButton.setTitle("←", for: .normal) backButton.setTitleColor(.blue, for: .normal) backButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) backButton.addTarget(self, action: #selector(onBackTapped), for: .touchUpInside) // Location Button locationButton.setTitle("📍", for: .normal) locationButton.setTitleColor(.blue, for: .normal) locationButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) locationButton.addTarget(self, action: #selector(onLocationTapped), for: .touchUpInside) // Title Label titleLabel.text = "设备列表" titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium) titleLabel.textColor = .red titleLabel.textAlignment = .center // Search Button searchButton.setTitle("🔍", for: .normal) searchButton.setTitleColor(.blue, for: .normal) searchButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) searchButton.addTarget(self, action: #selector(onSearchTapped), for: .touchUpInside) // Separator Line separatorLine.backgroundColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 0.3) // 添加所有子视图 addSubview(backButton) addSubview(locationButton) addSubview(titleLabel) addSubview(searchButton) addSubview(separatorLine) } // MARK: - 布局约束 override func makeConstraint() { // super.makeConstraint() backButton.snp.makeConstraints { make in make.leading.equalToSuperview().offset(16) make.centerY.equalToSuperview() make.width.greaterThanOrEqualTo(30) } locationButton.snp.makeConstraints { make in make.leading.equalTo(backButton.snp.trailing).offset(8) make.centerY.equalTo(backButton) make.size.equalTo(30) } titleLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.centerY.equalTo(backButton) } searchButton.snp.makeConstraints { make in make.trailing.equalToSuperview().offset(-16) make.centerY.equalTo(backButton) make.width.greaterThanOrEqualTo(30) } separatorLine.snp.makeConstraints { make in make.height.equalTo(1 / UIScreen.main.scale) make.leading.trailing.bottom.equalToSuperview() } } // MARK: - Action 处理 @objc private func onBackTapped() { onBackTap?() } @objc private func onLocationTapped() { onLocationTap?() } @objc private func onSearchTapped() { onSearchTap?() } }
最新发布
12-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值