swift - 自定义 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()
})
}
}
}
解决方案
想想你正在做的事情的顺序。你是说
profileView().token = filteredArray[indexPath.row].token
但是在下一行你说
profileView.create
它有什么作用?
profileView().token = "1"
首先你实例化一个 profileView 并设置它的令牌。然后你把它扔掉。然后实例化另一个profileView 并设置它的令牌(为 1)。因此,您的第一个代码也完全没用。
而且,profileView.create
还扔掉了它的profileView。因此,您的第二个代码完全没用。到目前为止,您已经创建并丢弃了两个视图。
最后,通过从 nib 加载它来创建第三个视图。那是你唯一真正做任何事情的人。但它只是一个 UIView,而不是 profileView,即使它是 profileView,你也永远不会设置它的令牌。
推荐阅读
- wordpress - 如何在wordpress 5.2中限制一个类别中的一篇文章
- powershell - 检查 AD 组是否为空
- python - 正则表达式:Python 与 SED 替换 URL 的 FQDN 但保留端口
- swift - 使用 Combine 时处理 Swift 5 排他性强制执行
- ios - 如何在 AVAudioSession 中使用 iPhone XS 内置麦克风的立体声(2 声道)?
- react-native - 用于身份验证、连接邀请和用户搜索的 Linkedin API
- python - NotImplementedError:这是语音识别中的一个抽象类
- r - R 中大型文本文件的大型语料库对象的示例输出
- symfony - 关于 getRepository Symfony 3 的 Foreach
- node.js - 通过节点请求模块下载的图像已损坏