Mapkit 을 배워보자 !!! - 2

godo·2022년 11월 5일
0

Mapkit

목록 보기
2/2

경로 찾기

import Contacts
...
var mapItem: MKMapItem? {
    guard let location = locationName else {
        return nil
    }
    
    let addressDict = [CNPostalAddressStreetKey: location]
    let placemark = MKPlacemark(
        coordinate: coordinate,
        addressDictionary: addressDict
    )
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = title
    return mapItem
}

Artwork 클래스 파일에서 변경 사항


func mapView(
    _ mapView: MKMapView,
    annotationView view: MKAnnotationView,
    calloutAccessoryControlTapped control: UIControl
) {
    guard let artwork = view.annotation as? Artwork else { return }
    
    let launchOptions = [
        MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
    ]
    artwork.mapItem?.openInMaps(launchOptions: launchOptions)
}

딜리게이트 메서드 추가

Annotation 커스텀

MKMarkerAnnotationView 커스텀

class ArtworkMarkerView: MKMarkerAnnotationView {
    override var annotation: MKAnnotation? {
        willSet {
            guard let artwork = newValue as? Artwork else {return}
            
            canShowCallout = true
            calloutOffset = CGPoint(x: -5, y: 5)
            rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            
            markerTintColor = UIColor.purple
            if let letter = artwork.discipline?.first {
                glyphText = String(letter)
            }
        }
    }
}

위에 annotation 관련 mapView 메서드 삭제

이미지 추가 - 1

var image: UIImage {
    return UIImage(named: "이미지이름")!
}

Artwork 파일

glyphImage =  artwork.image

ArtworkMarkerView 파일

이전에 glyphText 를 제거하고 glyphImage 로 변경

이미지 추가 - 2

class ArtworkView: MKAnnotationView {
    override var annotation: MKAnnotation? {
        willSet {
            guard let artwork = newValue as? Artwork else {return}
            
            canShowCallout = true
            calloutOffset = CGPoint(x: -5, y: 5)
            rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            
            image = artwork.image
        }
    }
}

등록

mapView.register(
            ArtworkView.self,
            forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier
        )

액세서리 뷰

let mapButton = UIButton(frame: CGRect(
    origin: CGPoint.zero,
    size: CGSize(width: 48, height: 48))
)

mapButton.setBackgroundImage(UIImage(named: "winning"), for: .normal)

rightCalloutAccessoryView = mapButton

레이블

let detailLabel = UILabel()
detailLabel.numberOfLines = 0
detailLabel.font = detailLabel.font.withSize(12)
detailLabel.text = artwork.discipline
detailCalloutAccessoryView = detailLabel

Reference

https://www.kodeco.com/7738344-mapkit-tutorial-getting-started#toc-anchor-011

profile
☀️☀️☀️

0개의 댓글