¿Cómo puedo centrar una UIView programáticamente sobre una UIView existente usando Autolayout?


En caso de un checkin Foursquare exitoso, my iPhone app shows agrega una vista en la parte superior de la vista que se muestra.

Quiero que la vista se centre en X e Y y que tenga un ancho y un alto definidos usando el diseño automático, pero no estoy seguro de qué restricciones agregar programáticamente. Sé cómo hacerlo en Storyboard, pero no estoy seguro de qué escribir exactamente el código para hacer lo mismo, ya que esta vista se agrega más tarde en respuesta a una acción exitosa en la aplicación.

No puedo conseguirlo funciona correctamente y el UIView tiene una punta que carga con loadNibNamed:.

SuccessView *successfulCheckInView = [[SuccessView alloc] initWithFrame:CGRectZero];
successfulCheckInView.placeNameLabel.text = properVenue.name;
successfulCheckInView.placeAddressLabel.text = properVenue.address;
successfulCheckInView.delegate = self;

[self.ownerVC.view addSubview:successfulCheckInView];
Author: Anthony Glyadchenko, 2013-08-28

1 answers

Prueba esto:

NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[superview addConstraint:xCenterConstraint];

NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[superview addConstraint:yCenterConstraint];

Actualizado para Swift:

NSLayoutConstraint(item: view1, attribute: .centerX, relatedBy: .equal, toItem: view2, attribute: .centerX, multiplier: 1, constant: 0).isActive = true

NSLayoutConstraint(item: view1, attribute: .centerY, relatedBy: .equal, toItem: view2, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
 74
Author: Eric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-28 15:53:41