Jak utworzyć etykietę UILabel round cornered na iPhonie?

Czy istnieje sposób na tworzenie okrągłych krzywych UILabel? Jeśli odpowiedź brzmi "nie", to jak można stworzyć taki obiekt?

Author: Piyush Dubey, 2009-02-04

16 answers

IOS 3.0 i nowsze

IPhone OS 3.0 i nowszy obsługuje właściwość cornerRadius na klasie CALayer. Każdy Widok ma instancję CALayer, którą można manipulować. Oznacza to, że można uzyskać zaokrąglone rogi w jednej linii:

view.layer.cornerRadius = 8;

Będziesz musiał #import <QuartzCore/QuartzCore.h> i połączyć się z frameworkiem QuartzCore, aby uzyskać dostęp do nagłówków i właściwości Calayera.

Przed iOS 3.0

Jednym ze sposobów na to, czego ostatnio użyłem, jest utworzenie podklasy UIView, która po prostu rysuje zaokrąglone prostokąt, a następnie zrobić UILabel lub, w moim przypadku, UITextView, subview wewnątrz niego. Konkretnie:

  1. Utwórz podklasę UIView i nadaj jej nazwę podobną do RoundRectView.
  2. w metodzie RoundRectView drawRect: Narysuj ścieżkę wokół granic widoku za pomocą podstawowych wywołań graficznych, takich jak CGContextAddLineToPoint() dla krawędzi i cgcontextaddarctopoint () dla zaokrąglonych narożników.
  3. Utwórz instancję UILabel i zrób z niej podgląd podrzędny RoundRectView.
  4. Ustaw ramkę etykieta ma być kilka pikseli w granicach RoundRectView. (Na przykład, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

Możesz umieścić RoundRectView na widoku za pomocą Kreatora interfejsu, jeśli utworzysz ogólny interfejs UIView, a następnie zmienisz jego klasę za pomocą Inspektora. Prostokąt będzie widoczny dopiero po skompilowaniu i uruchomieniu aplikacji, ale przynajmniej będziesz mógł umieścić subview i podłączyć go do gniazd lub akcji, jeśli zajdzie taka potrzeba.

 224
Author: benzado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-07 07:12:01

Dla urządzeń z systemem iOS 7.1 lub nowszym, należy dodać:

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;
 134
Author: OscarWyck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-09 12:50:06

Dla Swift iOS8 na podstawie OScarsWyck odpowiedź:

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
 18
Author: VBaarathi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 16:08:23
  1. masz UILabel o nazwie: myLabel.
  2. w pliku "m" lub "h" import: #import <QuartzCore/QuartzCore.h>
  3. W Twoim viewDidLoad Napisz ten wiersz: self.myLabel.layer.cornerRadius = 8;

    • zależy jak chcesz możesz zmienić wartość cornerRadius z 8 na inną liczbę:)

Powodzenia

 11
Author: Gabriel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-04 10:32:24

W ten sposób można wykonać zaokrąglone obramowanie o szerokości obramowania dowolnej kontrolki:-

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]];


Wystarczy zastąpić {[1] } swoim UILabel.

Uwaga: - nie zapomnij zaimportować <QuartzCore/QuartzCore.h>

 11
Author: Piyush Dubey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-13 08:09:36

Inną metodą jest umieszczenie png za UILabel. Mam widoki z kilkoma etykietami, które nakładają pojedynczy png tła, który zawiera wszystkie grafiki dla poszczególnych etykiet.

 6
Author: Alpinista,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-04 17:24:23

XCode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;
 6
Author: Ahmed Abdallah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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];
 4
Author: Gaurav Gilani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-21 06:44:52

Zrobiłem podklasę swift UILabel, aby osiągnąć ten efekt. Ponadto automatycznie ustawiam kolor tekstu na czarny lub biały dla maksymalnego kontrastu.

Wynik

kolory-zaokrąglone-obramowania

Used SO-Posts:

Plac zabaw

Po prostu wklej to do iOS "Plac zabaw": {]}

//: 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())
 4
Author: Besi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:25

Jeśli chcesz zaokrąglony róg obiektów UI, takich jak (UILabel, UIView, UIButton, UIImageView) przez storyboard następnie ustaw clip to bounds true i ustaw User Defined Runtime Attributes Key path jako layer.cornerRadius, Typ = liczba i wartość = 9 (jako twoje wymaganie)

Ustaw klip do granic jako Ustaw atrybuty Runtime zdefiniowane przez Użytkownika jako

 3
Author: Nikhlesh Bagdiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 10:49:47

W Monotouch / Xamarin.iOS rozwiązałem ten sam problem tak:

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;
 2
Author: Daniele D.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 14:23:05

Działa idealnie w 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

    }
 2
Author: Naishta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-16 22:02:15

Czy próbowałeś użyć UIButton z konstruktora interfejsu (który ma zaokrąglone rogi) i eksperymentować z ustawieniami, aby wyglądało to jak etykieta. jeśli wszystko, co chcesz, to wyświetlać statyczny tekst w środku.

 2
Author: Naren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-27 05:03:16

Działa dobrze w Xcode 8.1.2 z Swift 3, testowane w sierpniu 2017

"cornerRadius" jest kluczową właściwością do ustawiania zaokrąglonych krawędzi, gdzie jeśli używasz tego samego stylu dla wszystkich etykiet w aplikacji, polecam metodę rozszerzenia.

Kod:

 // 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
    }
}

Wyjście:

Tutaj wpisz opis obrazka

Dlaczego metoda rozszerzenia?

Utwórz plik Swift i dodaj następujący kod, który ma rozszerzenie metoda do klasy" UILabel", gdzie ta metoda jest zdefiniowana przez użytkownika, ale będzie działać dla wszystkich etykiet w aplikacji i pomoże zachować spójność i czysty kod, jeśli zmienisz dowolny styl w przyszłości wymagać tylko w metodzie rozszerzenia.

 2
Author: BHUVANESH MOHANKUMAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-15 13:25:06

Swift 3

Jeśli chcesz zaokrągloną etykietę z kolorem tła, oprócz większości innych odpowiedzi, musisz również ustawić kolor tła layer. Nie działa przy ustawianiu koloru tła view.

label.layer.cornerRadius = 8
label.layer.masksToBounds = true
label.layer.backgroundColor = UIColor.lightGray.cgColor

Jeśli używasz układu automatycznego, chcesz wprowadzić pewne wypełnienia wokół etykiety i nie chcesz ręcznie ustawiać rozmiaru etykiety, możesz utworzyć podklasę UILabel i nadpisać właściwość intrinsincContentSize:

class LabelWithPadding: UILabel {
    override var intrinsicContentSize: CGSize {
        let defaultSize = super.intrinsicContentSize
        return CGSize(width: defaultSize.width + 12, height: defaultSize.height + 8)
    }
}

Aby połączyć te dwa elementy, musisz również ustawić label.textAlignment = center, w przeciwnym razie tekst zostanie wyrównany do lewej.

 1
Author: Marián Černý,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-29 21:52:03

W zależności od tego, co dokładnie robisz, możesz zrobić obraz i ustawić go jako tło programowo.

 0
Author: Steven Mayer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-05 00:55:53