cornerRadius dejó de trabajar en Swift 2.3 / iOS 10 / Xcode 8


Tengo un cornerRadius establecido en un UIView y un UIImageView dentro del mismo UIView. Estoy calculando el radio de esquina con RockProfileView.frame.size.height / 2 pero el UIView dejó de mostrarse en iOS 10.

Después de verificar más, encontré que el valor de RockProfileView.frame.size.height / 2 está saliendo para ser 1000.0 mientras que la restricción de ancho y alto se establece en 64.0

Cuando codifiqué el RockProfileView.layer.cornerRadius = 32 a 64/2 funciona bien.

¿Cuál podría ser el problema ?

Código completo:

    RockProfileView.layer.cornerRadius = RockProfileView.frame.size.height / 2
    RockProfileView.clipsToBounds = true
    RockProgressView.layer.masksToBounds = true
Author: Ankit Khanna, 2016-09-15

12 answers

Como respondió Rob, he movido el código de viewDidLoad a viewDidAppear y el problema está solucionado.

O Agregar self.view.layoutIfNeeded() antes de su código en viewDidLoad también resuelve el problema.

En el caso de UITableViewCell, Dentro de awakeFromNib agregar [self layoutIfNeeded]; antes de actualizar el radio de esquina debe resolver todos los problemas.

 32
Author: Ankit Khanna,
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-10-03 05:49:04

Hice este código en awakeFromNib, pero después de actualizar a ios 10+xcode 8, dejó de funcionar.

Luego moví este código al método layoutSubViews. Entonces funcionó.

Esperando, esto será útil para usted.

Si todavía quieres hacer esto en awakefromnib, entonces haz esto después de poner un poco de retraso (usando dispatch_after o NSOperatinQueue o performSelectorWithDelay)

 8
Author: Mehul Thakkar,
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-09-20 05:52:15

Si está dentro de su ViewControllers, en lugar de mover todas las operaciones de capa a viewDidLayer, mueva ese código dentro de DispatchQueue. Esto funcionó para mí:

DispatchQueue.main.async {
            let layer = self.signUpBtn.layer
            layer.borderColor = UIColor.white.cgColor
            layer.borderWidth = 2 / UIScreen.main.scale
        }

Espero que esto te ayude

 4
Author: YPK,
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-09-22 19:46:14

Una cosa nueva en XCode8 no podemos establecer directamente el Cornerrius de la capa.

Cuando se desea aplicar cornerRadius de UIView necesidad de agregar una línea de código antes de aplicar cornerRadius.

Tu botón.layoutIfNeeded ()

Ejemplo en el Objetivo C.

[yourButton layoutIfNeeded];
yourButton.layer.cornerRadius = yourButton.frame.size.height/2;
[[yourButton layer] setBorderWidth:2.0f];
Example into Swift3

self.layoutIfNeeded()
yourButton.layer.cornerRadius = self.frame.height / 2.0
yourButton.layer.borderWidth = 2.0
 3
Author: Sunil aruru,
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-10-07 06:08:46

Para mí, lo que funcionó primero fue llamar layoutIfNeeded y más tarde en el conjunto Cornerrius

 2
Author: Javier Calatrava Llavería,
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-09-28 12:35:32

Swift 3

Intentaré este código para definir el radio de esquina de UIImageView

 imgProfile.layer.cornerRadius = imgProfile.frame.size.width / 2
            imgProfile.clipsToBounds = true
 1
Author: Rob-4608,
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
2017-05-18 09:54:35

Marcados con @IBInspectable en swift (o IBInspectable en Objective-C), son fácilmente editables en el panel inspector de atributos de Interface Builder.
Puede establecer directamente Cornerrius en el inspector de atributos

extension UIView {

  @IBInspectable var cornerRadius: CGFloat {

   get{
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue
        layer.masksToBounds = newValue > 0
    }
  }
}
 1
Author: Amit Jagesha シ,
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
2017-06-02 09:11:31

Tuve el mismo problema, solo iOS 10. Descubrí que viewDidLayoutSubviews o viewDidLoad (posiblemente otros también, pero no lo comprobé) solo funcionaban si envolvía el código de diseño en la cola de despacho como YPK sugirió.

Estoy usando Xamarin así que la sintaxis es un poco diferente:

DispatchQueue.MainQueue.DispatchAsync(() =>
        {
            SetYourViewProperties();
        });
 0
Author: Ryan,
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-09-23 13:22:52

Tuve que ejecutarlo en el hilo principal para que funcionara.

    dispatch_async(dispatch_get_main_queue(), ^{
       [imageView.layer setCornerRadius:4];
       [imageView.layer setMasksToBounds:YES];
});
 0
Author: nithinreddy,
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-10-02 05:57:51

Como se mencionó en una respuesta anterior, agregar self.layoutIfNeeded() antes de cambiar el radio de esquina funcionó para mí.

 0
Author: A. Edwards,
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-05 18:35:36

Solución Swift 3.2

En caso de que alguien todavía tenga este problema, resolví el problema redondeando las celdas (o cualquiera de sus subviews) en viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    if (tableView.visibleCells.count > 0) {
        for cell in tableView.visibleCells {
            let customCell = cell as! CustomCell
            // Use any rounding method you use
            customCell.exampleSubview.roundCorners(corners: .allCorners, radius: 6) 
            customCell.exampleSubview.layoutIfNeeded()
        }
    }
}
 0
Author: Herman Coma,
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
2017-12-31 14:33:34

En WWDC 2016 / Qué hay de nuevo en el Diseño automático, Apple recomienda una forma de diseño automático llamada

Adoptando gradualmente el Diseño automático

Significa que si el diseño es fácil, puede usar autoresizing. Y se traducirá en restricciones en tiempo de ejecución.

Así que una de las soluciones es utilizar autoresizing, y se puede obtener el marco correcto sobre la vista en cualquier momento. Pero la premisa es que el autoresizing puede satisfacer su diseño

 -1
Author: user6124146,
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-09-28 03:21:50