【问题标题】:Not sure why my custom UICollectionViewCell isn’t working?不知道为什么我的自定义 UICollectionViewCell 不起作用?
【发布时间】:2020-05-15 04:16:48
【问题描述】:

我正在 Swift Playgrounds for iPad 中编写一个模拟消息应用程序。每次我运行 Playground 时,都会收到错误消息“运行此页面时出现问题。检查您的代码是否存在问题。如果您卡住了,请删除此页面上的所有内容,然后重试”。这是我到目前为止所拥有的。这很简单,我不确定我做错了什么。

import UIKit
import PlaygroundSupport

class ChatView : UICollectionViewController, UICollectionViewDelegateFlowLayout {
    override func viewDidLoad(){
        super.viewDidLoad()
        collectionView.register(ChatLogMessageCell.self, forCellWithReuseIdentifier: "cellId")
    }

        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! ChatLogMessageCell
            cell.messageTextView.text = "sample message text"
            return cell
        }

}



class ChatLogMessageCell : UICollectionViewCell {
    let messageTextView : UITextView = {
        let textView = UITextView()
        //textView.font = UIFont.systemFont(ofSize: 36)
        textView.text = "sample message"
        return textView
    }()

    func setupViews(){
        addSubview(messageTextView)
    }
}

PlaygroundPage.current.liveView = ChatView()

【问题讨论】:

  • 游乐场往往是越野车。您是否尝试过在普通项目中运行它?
  • 您没有为 textview 设置任何约束?
  • 不幸的是,这必须在操场上完成。这是 Apple WWDC 学生挑战赛的参赛作品,要求所有参赛作品都是 Playgrounds。

标签: ios swift uikit


【解决方案1】:

请尝试此解决方案。

import UIKit
import PlaygroundSupport

class ChatView : UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = .green
        return cell
    }

}

PlaygroundPage.current.liveView = ChatView(collectionViewLayout: UICollectionViewFlowLayout())

【讨论】:

  • 不幸的是它仍然给出同样的错误信息
  • 你是否在 Xcode 11.4.1 中检查了这个,因为这在我的操场上运行完美
  • 重新启动一切,现在一切正常。谢谢!
  • 欢迎朋友,如果您的问题解决了,请接受我的回答。
猜你喜欢
  • 2016-08-25
  • 2013-11-27
  • 1970-01-01
  • 2020-09-19
  • 2014-01-17
  • 2015-06-25
  • 2019-05-27
  • 2021-06-07
  • 2019-06-20
相关资源
最近更新 更多