我的目標是為 MKAnnotationView 創建自定義影像。

每個注釋的影像中“服務專案”的數量可能不同 -> 應該可以動態更改視圖中的專案。
我的想法是創建自定義 UIView (xib),以編程方式加載 xib 并動態更改專案。然后我會將 UIView 轉換為 UIImage。
//ServiceAnnotationView.xib

//ServiceAnnotationView.class
class ServiceAnnotationView: UIView{
}
//擴展 UIView -> 可以從代碼中加載 xib 檔案
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
動態創建注釋影像。
let view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
let serviceAnnotationView: ServiceAnnotationView = ServiceAnnotationView.fromNib()
view.image = serviceAnnotationView.asImage()
顯示 2 項時的結果:

顯示 1 個專案時的結果

在這種情況下,UIView 應該會自動縮小。UIView 的寬度總是一樣的。無論 UIStackView 中有多少項。
到目前為止我嘗試了什么?我試圖根據專案數為 UIView 指定框架。-> 沒有成功
然后我根據專案數更改 UIView 的約束大小。-> 沒有成功
由于 UIStackView,UIView 應該會自動調整大小。為什么在這種情況下沒有發生?
uj5u.com熱心網友回復:
你遺漏了很多關于你的設定以及你如何實際嘗試使用它的資訊,但這可能會有所幫助......
假設你有:
- 一些 var/func 在你
ServiceAnnotationView的堆疊視圖中顯示/隱藏影像 - 你有一個作業
UIView擴展.asImage() - 您已經對影像設定了尺寸限制(例如高度和寬度)
打電話.setNeedsLayout()和打電話.layoutIfNeeded() 之前.asImage():
let serviceAnnotationView: ServiceAnnotationView = ServiceAnnotationView.fromNib()
// however you're setting the number of images to show in the stack view
serviceAnnotationView.numItems = 3
serviceAnnotationView.translatesAutoresizingMaskIntoConstraints = false
serviceAnnotationView.setNeedsLayout()
serviceAnnotationView.layoutIfNeeded()
let img = serviceAnnotationView.asImage()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474197.html
標籤:代码 uiview 西布 nslayoutconstraint uistackview
下一篇:XCodeAdmob構建失敗問題
