首页 > 解决方案 > 自定义 UIView 类中的 Swift 设置变量

问题描述

我已经从 xib (profileView) 设置了一个自定义视图。当在我的“chatPage”类中选择一个单元格时,我试图在配置文件类中设置令牌变量并在视图加载时打印它。

下面的代码不输出令牌,它是空的,我无法让它工作。

我将如何实现这一目标?

聊天页面.swift

  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       // Pass the user token to the profileView class.
        profileView().token = filteredArray[indexPath.row].token
         view.addSubview(profileView.create(height: view.frame.height, width: view.frame.width, x: view.frame.origin.x, y: view.frame.origin.y, tag: 104))
    }

自定义 profileView 类:

class profileView: UIView, UIScrollViewDelegate {

    var token: String?

    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var nameLabel: UILabel!

    static func create(height: CGFloat,width:CGFloat,x:CGFloat,y:CGFloat,tag: Int) -> UIView{
        profileView().token = "1"
        let key = UINib(nibName: "profileView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
        key.frame.size.height = height
        key.frame.size.width = width
        key.frame.origin.x = x
        key.frame.origin.y = y
        key.tag = tag
        return key
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        //custom logic goes here
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if(scrollView.contentOffset.y < -60){
            UIView.animate(withDuration: 1.0, delay: 0.0, options: [], animations: {
               self.frame.origin.y += self.frame.height
            }, completion: { (finished: Bool) in
                self.removeFromSuperview()
            })
        }
    }

}

标签: swift

解决方案


想想你正在做的事情的顺序。你是说

profileView().token = filteredArray[indexPath.row].token

但是在下一行你说

profileView.create

有什么作用?

profileView().token = "1"

首先你实例化一个 profileView 并设置它的令牌。然后你把它扔掉。然后实例化另一个profileView 并设置它的令牌(为 1)。因此,您的第一个代码也完全没用。

而且,profileView.create还扔掉了它的profileView。因此,您的第二个代码完全没用。到目前为止,您已经创建并丢弃了两个视图。

最后,通过从 ni​​b 加载它来创建第三个视图。那是你唯一真正做任何事情的人。但它只是一个 UIView,而不是 profileView,即使它是 profileView,你也永远不会设置它的令牌。


推荐阅读