【问题标题】:Display data from tableviewcell into Pop-up UIView将 tableviewcell 中的数据显示到 Pop-up UIView
【发布时间】:2022-01-18 19:39:52
【问题描述】:

我有一个 tableView 显示用户已经创建的多个任务。当用户单击任务(tableView 单元格)时,我想显示一个弹出窗口,显示有关用户任务的更多信息。我已经创建了 popUp 视图,它显示正常,但数据(类别、日期、小时)没有显示在 popUp 中。当用户单击该行时,我不知道如何访问我的数据并将其放入弹出视图中。这是我到目前为止尝试过的:

MyTasksCollectionCell

enum DisplayedTasks {
    case current
    case past
}
class MyTasksCollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

var displayedTasks = DisplayedTasks.current

var tasks = [Add]()
var pastTasks = [Add]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! MyTasksTableCell
    cell.accessoryType = .disclosureIndicator
    let task = {() -> Add in
        switch (displayedTask) {
          case .current:
             // First segment tapped
            return self.tasks[indexPath.row]
          case past:
             // Second segment tapped
            return self.pastTasks[indexPath.row]
        }
    }()
         
    cell.categoryLabel.text =
        "\(task.category)"
    cell.dateLabel.text =
        "\(task.date)"
    cell.hourLabel.text =
        "\(task.hour)"

    return cell
      
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                 tableView.deselectRow(at: indexPath, animated: true)
 let task = {() -> Add in
        switch (displayedTask) {
          case .current:
             // First segment tapped
            return self.tasks[indexPath.row]
          case past:
             // Second segment tapped
            return self.pastTasks[indexPath.row]
        }
    }()
let selectedCell = tableView.cellForRow(at: indexPath) as? MyTasksDetailView//Warning message here !!! "Cast from 'UITableViewCell?' to unrelated type 'MyTasksDetailView' always fails"

selectedCell?.category.text = "\(task.category)"
selectedCell?.hour.text = "\(task.hour)"
selectedCell?.date.text = "\(task.date)"
print (selectedCell?.category.text)
    
    let popupView = MyTasksDetailView()
    UIApplication.shared.keyWindow?.addSubview(popupView)

}
extension UIApplication {
    var keyWindow: UIWindow? {
        // Get connected scenes
        return UIApplication.shared.connectedScenes
            // Keep only active scenes, onscreen and visible to the user
            .filter { $0.activationState == .foregroundActive }
            // Keep only the first `UIWindowScene`
            .first(where: { $0 is UIWindowScene })
            // Get its associated windows
            .flatMap({ $0 as? UIWindowScene })?.windows
            // Finally, keep only the key window
            .first(where: \.isKeyWindow)
    }
}

MyTasksDetailView

class MyTasksDetailView: UIView  {
      
     var setCategory: String? {
        didSet {
            categoryLabel.text = setCategory ?? ""
        }
    }
    var setDate: String? {
        didSet {
            dateLabel.text = setDate ?? ""
        }
    }
      var setHour: String? {
        didSet {
            hourLabel.text = setHour ?? ""
        }
    }
     let categoryLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 28, weight: .bold)
//        label.text = "category"
        label.textAlignment = .center
        label.textColor = .label

        return label
    }()

     let dateLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
//        label.text = "date"
        label.textAlignment = .center
        label.numberOfLines = 3
        label.textColor = .label
        return label
    }()
let hourLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
//        label.text = "hour"
        label.textAlignment = .center
        label.numberOfLines = 3
        label.textColor = .label
        return label
    }()
     let container: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.clipsToBounds = true
        v.backgroundColor = .white
        v.layer.cornerRadius = 24

        v.backgroundColor =
            // 1
            UIColor { traitCollection in
              // 2
              switch traitCollection.userInterfaceStyle {
              case .dark:
                // 3
                 v.layer.borderColor = UIColor.label.cgColor
                return UIColor.systemBackground

              default:
                // 4
                 v.layer.borderColor = UIColor.black.cgColor
                return UIColor.systemBackground
              }
            }
        return v
    }()

     lazy var stack: UIStackView = {
        let stack = UIStackView(arrangedSubviews: [categoryLabel, dateLabel, hourLabel])
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .vertical
        return stack
    }()
    @objc func animateOut() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
            self.container.transform = CGAffineTransform(translationX: 0, y: -self.frame.height)
            self.alpha = 0
        }) { (complete) in
            if complete {
                self.removeFromSuperview()
            }
        }
    }
    @objc func animateIn() {
        self.container.transform = CGAffineTransform(translationX: 0, y: -self.frame.height)
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
            self.container.transform = .identity
            self.alpha = 1
        })
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(animateOut)))
       
        let blurEffect = UIBlurEffect(style: .dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.alpha = 1
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.addSubview(blurEffectView)
        
        self.frame = UIScreen.main.bounds
        self.addSubview(container)
      
        container.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        container.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        container.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.7).isActive = true
        container.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.45).isActive = true
        
        container.addSubview(stack)
        stack.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
        stack.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
        stack.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
        stack.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 0.5).isActive = true
        
        animateIn()
     }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

添加(数据结构)

struct Add {
    static var details: Add = Add()
    var category: String = ""
    var date: String = ""
    var hour: String = ""
    var id: String?
    
    func getDict() -> [String: Any] {
              let dict = ["category": self.category,
                          "date": self.date,
                          "hour": self.hour,
                ] as [String : Any]
               return dict
         }

}

【问题讨论】:

  • 这看起来很像你之前的问题:stackoverflow.com/questions/70292528/… ... 我给你的答案应该和这个问题几乎一样。而且没有理由这样做:UIApplication.shared.keyWindow?.addSubview(popupView)
  • @DonMag 我更改了我的代码以显示一个弹出窗口(更实用),但它使您的代码无法使用,因为它不再是 viewController,我也尝试使用您的代码但无法制作它适用于我的:/ PS:UIApplication.shared.keyWindow?.addSubview(popupView) 没有这个弹出窗口只显示在屏幕底部的 tableView 内)而不是屏幕中间......

标签: ios swift xcode uitableview uiview


【解决方案1】:

我看不到您将所需数据设置到 MyTasksDetailView 的位置。

将属性“任务”添加到 MyTasksDetailView(找不到任务实例的类型,所以在我的示例中我使用了任务)

internal var task: Task? {
   didSet {
        if let task = task {
            setCategory = task.category
            setDate = task.date
            setHour =  task.hour
        }
    }
}

并在初始化后设置

let popupView = MyTasksDetailView()
popupView.task = task
UIApplication.shared.keyWindow?.addSubview(popupView)

【讨论】:

  • 我在 MyTasksDetailView 中添加了该属性,并在我的 didselect 中添加了popupView.task = task,但出现“无法在范围内找到'任务'”的错误提示
  • 如果您只需要显示带有单元格数据的 popupView,您可以使用 selectedCell 删除代码并设置其属性(这不起作用,因为您尝试将单元格转换为自定义视图,当所有您可以转换为 MyTasksTableCell,就像您在 CellForRaw 中设置的那样)。 “在范围内找不到‘任务’” - 在定义“任务”常量的范围内执行此操作。
  • 没关系!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多