¿Cómo puedo crear una UILabel redonda en el iPhone?
¿Hay una forma incorporada de crear UILabels con esquinas redondeadas? Si la respuesta es no, ¿cómo se podría crear tal objeto?
16 answers
IOS 3.0 y posteriores
IPhone OS 3.0 y posterior soporta la propiedad cornerRadius
en la clase CALayer
. Cada vista tiene una instancia CALayer
que puede manipular. Esto significa que puede obtener esquinas redondeadas en una línea:
view.layer.cornerRadius = 8;
Necesitará #import <QuartzCore/QuartzCore.h>
y enlazar al framework QuartzCore para obtener acceso a las cabeceras y propiedades de CALayer.
Antes de iOS 3.0
Una forma de hacerlo, que usé recientemente, es crear una subclase UIView que simplemente dibuja un redondeado rectángulo, y luego hacer el UILabel o, en mi caso, UITextView, un subview dentro de él. Específicamente:
- Crea una subclase
UIView
y nómbrala comoRoundRectView
. - En el método
RoundRectView
, dibuja una ruta alrededor de los límites de la vista usando llamadas a gráficos principales como CGContextAddLineToPoint() para los bordes y CGContextAddArcToPoint() para las esquinas redondeadas. - Cree una instancia
UILabel
y conviértala en una subview de la RoundRectView. - Establecer el marco de la etiqueta debe ser un recuadro de unos cuantos píxeles de los límites de RoundRectView. (Por ejemplo,
label.frame = CGRectInset(roundRectView.bounds, 8, 8);
)
Puede colocar el RoundRectView en una vista usando Interface Builder si crea una UIView genérica y luego cambia su clase usando el inspector. No verá el rectángulo hasta que compile y ejecute su aplicación, pero al menos podrá colocar la subview y conectarla a outlets o acciones si es necesario.
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
2018-02-07 07:12:01
Para dispositivos con iOS 7.1 o posterior, debe agregar:
yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;
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
2015-07-09 12:50:06
Para Swift IOS8 en adelante basado en OScarsWyck respuesta:
yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
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
2015-08-17 16:08:23
- tienes un
UILabel
llamado:myLabel
. - en su importación de archivo" m "o" h":
#import <QuartzCore/QuartzCore.h>
-
En tu
viewDidLoad
escribe esta línea:self.myLabel.layer.cornerRadius = 8;
- depende de cómo desee puede cambiar el valor de cornerRadius de 8 a otro número:)
Buena suerte
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
2012-12-04 10:32:24
Puede hacer borde redondeado con el ancho del borde de cualquier control de esta manera:-
CALayer * l1 = [lblName layer];
[l1 setMasksToBounds:YES];
[l1 setCornerRadius:5.0];
// You can even add a border
[l1 setBorderWidth:5.0];
[l1 setBorderColor:[[UIColor darkGrayColor] CGColor]];
Simplemente reemplace lblName
con su UILabel
.
Nota: - No olvides importar <QuartzCore/QuartzCore.h>
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
2014-02-13 08:09:36
Otro método es colocar un png detrás de la etiqueta UILabel. Tengo vistas con varias etiquetas que superponen un único png de fondo que tiene todas las ilustraciones para las etiquetas individuales.
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
2009-02-04 17:24:23
XCode 7.3.1 iOS 9.3.2
_siteLabel.layer.masksToBounds = true;
_siteLabel.layer.cornerRadius = 8;
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-07-21 11:22:58
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
label.text = @"Your String.";
label.layer.cornerRadius = 8.0;
[self.view addSubview:label];
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
2014-05-21 06:44:52
Hice una subclase swift UILabel
para lograr este efecto. Además, establezco automáticamente el color del texto en blanco o negro para un contraste máximo.
Resultado
Usado SO-Mensajes:
- ¿Cómo dibujar la frontera alrededor de UILabel?
- Añadir un borde fuera de un UIView
- Compruebe si el color UIColor es oscuro o brillante?
Patio de recreo
Simplemente pega esto en un iOS Zona de juegos:
//: Playground - noun: a place where people can play
import UIKit
class PillLabel : UILabel{
@IBInspectable var color = UIColor.lightGrayColor()
@IBInspectable var cornerRadius: CGFloat = 8
@IBInspectable var labelText: String = "None"
@IBInspectable var fontSize: CGFloat = 10.5
// This has to be balanced with the number of spaces prefixed to the text
let borderWidth: CGFloat = 3
init(text: String, color: UIColor = UIColor.lightGrayColor()) {
super.init(frame: CGRectMake(0, 0, 1, 1))
labelText = text
self.color = color
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup(){
// This has to be balanced with the borderWidth property
text = " \(labelText)".uppercaseString
// Credits to https://stackoverflow.com/a/33015915/784318
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
backgroundColor = color
layer.borderColor = color.CGColor
layer.masksToBounds = true
font = UIFont.boldSystemFontOfSize(fontSize)
textColor = color.contrastColor
sizeToFit()
// Credits to https://stackoverflow.com/a/15184257/784318
frame = CGRectInset(self.frame, -borderWidth, -borderWidth)
}
}
extension UIColor {
// Credits to https://stackoverflow.com/a/29044899/784318
func isLight() -> Bool{
var green: CGFloat = 0.0, red: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let brightness = ((red * 299) + (green * 587) + (blue * 114) ) / 1000
return brightness < 0.5 ? false : true
}
var contrastColor: UIColor{
return self.isLight() ? UIColor.blackColor() : UIColor.whiteColor()
}
}
var label = PillLabel(text: "yellow", color: .yellowColor())
label = PillLabel(text: "green", color: .greenColor())
label = PillLabel(text: "white", color: .whiteColor())
label = PillLabel(text: "black", color: .blackColor())
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-23 12:18:25
Si desea esquinas redondeadas de objetos de interfaz de usuario como (UILabel
, UIView
, UIButton
, UIImageView
) por storyboard luego establecer clip to bounds
true y establecer User Defined Runtime Attributes
Ruta de la clave como
layer.cornerRadius
, tipo = Número y valor = 9 (como su requisito)
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-28 10:49:47
En Monotouch / Xamarin.iOS resolví el mismo problema así:
UILabel exampleLabel = new UILabel(new CGRect(0, 0, 100, 50))
{
Text = "Hello Monotouch red label"
};
exampleLabel.Layer.MasksToBounds = true;
exampleLabel.Layer.CornerRadius = 8;
exampleLabel.Layer.BorderColor = UIColor.Red.CGColor;
exampleLabel.Layer.BorderWidth = 2;
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-01-14 14:23:05
Funciona perfectamente en Swift 2.0
@IBOutlet var theImage: UIImageView! //you can replace this with any UIObject eg: label etc
override func viewDidLoad() {
super.viewDidLoad()
//Make sure the width and height are same
self.theImage.layer.cornerRadius = self.theImage.frame.size.width / 2
self.theImage.layer.borderWidth = 2.0
self.theImage.layer.borderColor = UIColor.whiteColor().CGColor
self.theImage.clipsToBounds = true
}
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-04-16 22:02:15
¿Intentaste usar el UIButton
del creador de interfaces (que tiene esquinas redondeadas) y experimentar con la configuración para que parezca una etiqueta? si todo lo que desea es mostrar texto estático dentro.
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-04-27 05:03:16
Funciona bien en Xcode 8.1.2 con Swift 3, Probado durante AGOSTO de 2017
"Cornerrius" es la propiedad clave para establecer los bordes redondeados, donde si está utilizando el mismo estilo para todas las etiquetas en su aplicación, recomendaría un método de extensión.
Código:
// extension Class
extension UILabel {
// extension user defined Method
func setRoundEdge() {
let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
//Width of border
self.layer.borderWidth = 1.0
//How much the edge to be rounded
self.layer.cornerRadius = 5.0
// following properties are optional
//color for border
self.layer.borderColor = myGreenColor.cgColor
//color for text
self.textColor = UIColor.red
// Mask the bound
self.layer.masksToBounds = true
//clip the pixel contents
self.clipsToBounds = true
}
}
Salida:
¿Por qué método de extensión?
Cree un archivo Swift y agregue el siguiente código, que tiene la extensión método a la clase "UILabel", donde este método está definido por el usuario, pero funcionará para toda la etiqueta en su aplicación y ayudará a mantener la consistencia y el código limpio, si cambia cualquier estilo en el futuro solo se requiere en el método de extensión.
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-08-15 13:25:06
Swift 3
Si desea una etiqueta redondeada con color de fondo, además de la mayoría de las otras respuestas, también debe establecer el color de fondo de layer
. No funciona cuando se establece el color de fondo view
.
label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor
Si está utilizando auto layout, desea un poco de relleno alrededor de la etiqueta y no desea establecer el tamaño de la etiqueta manualmente, puede crear una subclase UILabel y anular la propiedad intrinsincContentSize
:
class LabelWithPadding: UILabel {
override var intrinsicContentSize: CGSize {
let defaultSize = super.intrinsicContentSize
return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
}
}
Para combinar los dos también tendrá que establecer label.textAlignment = center
, de lo contrario, el texto quedaría alineado a la izquierda.
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-29 21:52:03
Dependiendo de lo que esté haciendo exactamente, podría hacer una imagen y establecerla como fondo programáticamente.
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
2011-11-05 00:55:53