首页 > 解决方案 > 集合视图单元格内的 MKMapview 不可见

问题描述

我创建了一个包含 4 个单元格的集合视图。在其中一个中,我想显示一个 MapView。这是我的收藏视图单元格代码:

import Foundation
import UIKit
import MapKit
import CoreLocation

class PestañaUno: UICollectionViewCell, CLLocationManagerDelegate, MKMapViewDelegate
{
    let manager = CLLocationManager()

    override init(frame: CGRect)
    {
        super.init(frame: frame)
        Setup()
    }

    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

    var Mapa: MKMapView =
    {
        var map = MKMapView()
        map.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
        map.mapType = MKMapType.standard
        return map
    }()

    func Setup()
    {
        addSubview(Mapa)
    }

这是我尝试调用该 collectionviewcell 代码的时候。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    if indexPath.item == 1
    {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PestañaUno", for: indexPath) as! PestañaUno
    }

    return myCell
}

标签: iosswiftuicollectionviewmapkit

解决方案


试试下面的代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: 100, height: 100)
}

不要忘记实现委托方法。

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return [YOUR ITEM COUNT]
}

推荐阅读