Home > Enterprise >  Custom UIView from XIB not resizing
Custom UIView from XIB not resizing

Time:05-13

My aim is to create custom image for MKAnnotationView. enter image description here

The number of "service items" in image can be different for every annotation -> it should be possible to dynamically change items in view.

My idea was to create custom UIView (xib), load xib programmatically and change items dynamically. Then I would convert UIView to UIImage.

//ServiceAnnotationView.xib

enter image description here

//ServiceAnnotationView.class
class ServiceAnnotationView: UIView{
    
}

//extension UIView -> possible to load xib file from code

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
    }

Creating annotation image dynamically.

let view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
let serviceAnnotationView: ServiceAnnotationView = ServiceAnnotationView.fromNib()
view.image = serviceAnnotationView.asImage()

Result when showing 2 items:

enter image description here

Result when showing 1 items

enter image description here

In this case the UIView should automatically shrink. The width of UIView is always the same. No matter how many items are present in UIStackView.

What I have tried so far? I was trying to specify frame for UIView based on number of items. -> no success

Then I was changing constraint size of UIView based on number of items. -> no success

The UIView should automatically resize due to UIStackView. Why in this case is not happening?

CodePudding user response:

You've left out a lot of information about your setup and how you're actually trying to use this, but this might help...

Assuming you have:

  • some var/func in your ServiceAnnotationView to show/hide the images in the stack view
  • you have a working UIView extension for .asImage()
  • you've set sizing constraints on the images (e.g. Height and Width)

Call .setNeedsLayout() and .layoutIfNeeded() before calling .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()
  • Related