eemmrrkk
eemmrrkk

Reputation: 1710

Swift: NSCollectionViewItem properties not change

I am building a Cocoa Swift app which have NSCollectionViews and have an NSCollectionView which has custom NSCollectionViewItem which has like below as in photo.

enter image description here

My purpose is building something like a calendar and as you understand from the image, I want to change date value and date string. Even tried it like below couldn't achieve it and did not understand what effects it.

Here is my custom NSCollectionViewItem

class CalendarDateCell: NSCollectionViewItem {

    
    @IBOutlet weak var dateNameString: NSTextField!
    @IBOutlet weak var dateNumberString: NSTextField!
    
    
    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
    }
    
}

Here is my itemForRepresentedObjectAt function.

func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        // 4
        let item = calendarCollectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CalendarDateCell"), for: indexPath)
        guard let collectionViewItem = item as? CalendarDateCell else {return item}
        
        
        
        switch indexPath.item % 3 {
        case 0,1:
            collectionViewItem.dateNameString.stringValue = "0-1"
        case 2:
            collectionViewItem.dateNameString.stringValue = "3"
        default:
            break
        }
        
        return collectionViewItem
    }

I tried it for testing, UI is done work but I did not change the property of the NSCollectionViewItem as a change of NSIndexPath

Then I added a String variable to NSCollectionViewItem and observe it with didSet method and I can change the variable but it's not effective for UI elements of AppKit.

How can I fix the problem? Any suggestions?

Edit:

I add a model for NSCollectionViewItem

var calendarModel: CalendarModel = CalendarModel() {
        didSet {
            dateNameString.stringValue = calendarModel.name
        }
    }

Then change it in controller as

collectionViewItem.calendarModel.name = "1231"

but never affects.

Thanks in advance

Upvotes: 1

Views: 175

Answers (0)

Related Questions