0
votes

The problem

I'm stuck in a (I hope) simple problem: I have a custom XIB to show instead of the default MKAnnotationView in a map; my XIB has only a UILabel inside with some auto layout constraints.

The problem is that this UILabel is multiline (lines is set to 0) and it could be like 1 line or like 8 lines; so I need to fit the XIB's height to this label but I don't know how to achieve that.

What I have tried

Different layout constraints for the label but with no great results.

  • 1° solution

XIB:

Result:

  • 2° solution

XIB:

Result:

  • 3° solution

XIB:

Result:

The code

// inside view controller

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView)
{
    if view.annotation!.isKindOfClass(MKUserLocation)
    {
        return
    }

    let customView = (NSBundle.mainBundle().loadNibNamed("PinView", owner: self, options: nil))[0] as! PinView;

    var calloutViewFrame = customView.frame;
    calloutViewFrame.origin = CGPointMake(-calloutViewFrame.size.width/2 + 15, -calloutViewFrame.size.height);
    customView.frame = calloutViewFrame;
    customView.content.text = "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test "
    view.addSubview(customView)
}

...

class PinView: UIView
{
    @IBOutlet weak var content: UILabel!

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
    // Drawing code
    }
    */
}

I know that the XIB's dimension could be set from the size inspector in IB or by code but I can't find a effective solution for automatically fit the height of the UILabel.

1

1 Answers

2
votes

Use your 1 st solution and then

Only need to set the height constraint to Greater than or equal to

For more reference follow this answer in stackoverflow link