我有一個UITableView用于顯示我的應用程式設定的部分。該表的資料是dictionary. 表中的每個都cell包含一個title,description和一個switch來表示設定狀態。
每當用戶與其中一個開關互動時——至少一個表格單元格中的描述會在視覺上消失——即使相關字串仍然存在于資料字典中。
這幾天我一直在琢磨它。我錯過了什么或做錯了什么?
這是我的資料字典:
var appSettings: [String:SettingModel] = [
"Search results": SettingModel(
sectionTitle: "Search results",
options: [
"Save filters": SingleSetting (
title: "Save filters",
description: "Allow us to save filters when entering back to the app",
status: .off
),
"Save search results": SingleSetting (
title: "Save search results",
description: "Allow us to save your search result preferences for next search",
status: .off
)
]
),
"App preferences": SettingModel(
sectionTitle: "App preferences",
options: [
"Notification": SingleSetting (
title: "Notification",
description: "",
status: .on
)
]
)
]
這是我的 UITableView 代碼:
設定表格視圖 -
func setupTableView() {
tableView.register(UINib(nibName: Constants.NibNames.APP_SETTING, bundle: nil), forCellReuseIdentifier: Constants.TableCellsIdentifier.SETTING)
tableView.register(UINib(nibName: Constants.NibNames.APP_SETTING_SECTION, bundle: nil), forHeaderFooterViewReuseIdentifier: Constants.TableCellsIdentifier.SETTING_SECTION)
tableView.dataSource = self
tableView.delegate = self
}
我的 TableView 委托功能 -
// MARK: - UITableViewDataSource
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.appSettings.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionKey = viewModel.sectionsSortedKeys[section]!
return viewModel.appSettings[sectionKey]!.options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.TableCellsIdentifier.SETTING, for: indexPath) as! AppSettingCell
cell.delegate = self
let sectionKey = viewModel.sectionsSortedKeys[indexPath.section]!
var rowKey: String {
switch sectionKey {
case Constants.AppSettingsSectionTitles.SEARCH:
if indexPath.row == 1 {
return Constants.AppSettings.SAVE_FILTERS
} else {
return Constants.AppSettings.SEARCH_RESULTS
}
case Constants.AppSettingsSectionTitles.PREFERENCES:
return Constants.AppSettings.NOTIFICATION
default:
return ""
}
}
cell.settingTitle.text = viewModel.appSettings[sectionKey]!.options[rowKey]?.title
cell.settingDescription.text = viewModel.appSettings[sectionKey]!.options[rowKey]?.description
var settingSwitchImage: UIImage
switch viewModel.appSettings[sectionKey]!.options[rowKey]?.status {
case .on:
settingSwitchImage = UIImage(named: "switch-on")!
break
case .off:
settingSwitchImage = UIImage(named: "switch-off")!
break
default:
settingSwitchImage = UIImage(named: "switch-disabled")!
break
}
cell.settingSwitchImageView.image = settingSwitchImage
return cell
}
}
// MARK: - UITableViewDelegate
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: Constants.TableCellsIdentifier.SETTING_SECTION) as! SettingSectionCell
view.sectionLabel.text = viewModel.sectionsSortedKeys[section]
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 32
}
}
而我的細胞委托功能 -
// MARK: - AppSettingCellDelegate
extension SettingsViewController: AppSettingCellDelegate {
func settingCellDidPress(settingText: String) {
print("CURRENT APP SETTINGS ARRAY:")
print(self.viewModel.appSettings)
viewModel.updateSetting(settingTitle: settingText) {
DispatchQueue.main.async {
print("UPDATED APP SETTINGS ARRAY:")
print(self.viewModel.appSettings)
self.tableView.reloadData()
}
}
}
}
我的 AppSettingsCell 代碼 -
protocol AppSettingCellDelegate {
func settingCellDidPress(settingText: String)
}
class AppSettingCell: UITableViewCell {
@IBOutlet weak var settingTitle: UILabel!
@IBOutlet weak var settingDescription: UILabel!
@IBOutlet weak var settingSwitchImageView: UIImageView!
var delegate: AppSettingCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setTextLineSpacing()
setCellColorDesign()
setGestureRecognizer()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setTextLineSpacing() {
let attributedString = NSMutableAttributedString(string: settingDescription.text!)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
settingDescription.attributedText = attributedString
}
func setCellColorDesign() {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.clear
self.selectedBackgroundView = bgColorView
}
func setGestureRecognizer() {
settingSwitchImageView.addGestureRecognizer(UITapGestureRecognizer(target: settingSwitchImageView, action: #selector(switchWasPressed)))
settingSwitchImageView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(switchWasPressed(tapGestureRecognizer:)))
settingSwitchImageView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func switchWasPressed(tapGestureRecognizer: UITapGestureRecognizer) {
delegate?.settingCellDidPress(settingText: settingTitle.text!)
}
}
我的 ViewModel.updateSettings 功能:
func updateSetting(settingTitle: String, completionHandler: @escaping (Int?, Int?) -> ()) {
var sectionTitle: String? = nil
var sectionIndex: Int? = nil
if appSettings[Constants.AppSettingsSectionTitles.SEARCH]?.options[settingTitle] != nil {
sectionTitle = Constants.AppSettingsSectionTitles.SEARCH
sectionIndex = 0
} else if appSettings[Constants.AppSettingsSectionTitles.PREFERENCES]?.options[settingTitle] != nil {
sectionTitle = Constants.AppSettingsSectionTitles.PREFERENCES
sectionIndex = 1
}
if let sectionTitle = sectionTitle {
let currentStatus = appSettings[sectionTitle]?.options[settingTitle]?.status
var newStatus: SwitchStatus = .off
if currentStatus != .disabled {
if currentStatus == .on {
appSettings[sectionTitle]?.options[settingTitle]?.status = newStatus // update local array
} else {
newStatus = .on
appSettings[sectionTitle]?.options[settingTitle]?.status = newStatus // update local array
}
let settingIndex = appSettings[sectionTitle]?.options[settingTitle]?.index
repository.updateSavedSetting(settingTitle: settingTitle, newStatus: newStatus) {
completionHandler(sectionIndex, settingIndex)
}
}
}
}
以及它導致的存盤庫功能:
func updateSavedSetting(settingTitle: String, newStatus: SwitchStatus, completionHandler: @escaping () -> ()) {
switch settingTitle {
case Constants.AppSettings.SAVE_FILTERS:
userDefaultsManager.setItemToUserDefaults(key: Constants.UserDefaults.SAVE_FILTERS, data: newStatus.rawValue)
case Constants.AppSettings.SEARCH_RESULTS:
userDefaultsManager.setItemToUserDefaults(key: Constants.UserDefaults.SAVE_SEARCH_RESULTS, data: newStatus.rawValue)
if newStatus == .off {
userDefaultsManager.clearSingleKeyValuePairFromUserDefaults(keyToRemove: Constants.UserDefaults.RECENT_SEARCHES)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: Constants.NotificationCenter.RECENT_SEARCHES_EMPTIED), object: nil)
}
case Constants.AppSettings.NOTIFICATION:
userDefaultsManager.setItemToUserDefaults(key: Constants.UserDefaults.SEND_NOTIFICATIONS, data: newStatus.rawValue)
default:
print("not valid option")
}
completionHandler()
}
當我在更新前后列印 appSettings 資料字典時 - 您可以看到所有描述仍然存在:
CURRENT APP SETTINGS ARRAY:
["Search results": Dispatcher_Development.SettingModel(sectionTitle: "Search results", options: ["Save filters": Dispatcher_Development.SingleSetting(title: "Save filters", description: "Allow us to save filters when entering back to the app", status: Dispatcher_Development.SwitchStatus.on), "Save search results": Dispatcher_Development.SingleSetting(title: "Save search results", description: "Allow us to save your search result preferences for next search", status: Dispatcher_Development.SwitchStatus.on)]), "App preferences": Dispatcher_Development.SettingModel(sectionTitle: "App preferences", options: ["Notification": Dispatcher_Development.SingleSetting(title: "Notification", description: "", status: Dispatcher_Development.SwitchStatus.on)])]
UPDATED APP SETTINGS ARRAY:
["Search results": Dispatcher_Development.SettingModel(sectionTitle: "Search results", options: ["Save filters": Dispatcher_Development.SingleSetting(title: "Save filters", description: "Allow us to save filters when entering back to the app", status: Dispatcher_Development.SwitchStatus.off), "Save search results": Dispatcher_Development.SingleSetting(title: "Save search results", description: "Allow us to save your search result preferences for next search", status: Dispatcher_Development.SwitchStatus.on)]), "App preferences": Dispatcher_Development.SettingModel(sectionTitle: "App preferences", options: ["Notification": Dispatcher_Development.SingleSetting(title: "Notification", description: "", status: Dispatcher_Development.SwitchStatus.on)])]
編輯 -reloadRows(at:with:)我更新了我的代碼以使用該函式
僅重繪 相關行(而不是整個表) 。它在一定程度上改善了情況,但奇怪的消失仍然發生。
這是我的做法(正確的部分和行號在閉包中傳回):
// MARK: - AppSettingCellDelegate
extension SettingsViewController: AppSettingCellDelegate {
func settingCellDidPress(settingText: String) {
viewModel.updateSetting(settingTitle: settingText) { sectionIndex, settingIndex in
DispatchQueue.main.async {
let indexPath = IndexPath(row: settingIndex ?? 0, section: sectionIndex ?? 0 )
self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
}
}
}
}
這是您第一次進入頁面時的照片: 在此處輸入圖片描述
這是開始翻轉開關后頁面外觀的照片: 在此處輸入影像描述
uj5u.com熱心網友回復:
設法通過在函式中定義行高heightForRowAt并在我的自定義中重新安排約束來解決這個問題appSettingCell
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459733.html
