문제

둥근 코너가 달린 Uilabels를 만들 수있는 내장이 있습니까? 대답이 아니오라면 어떻게 그러한 객체를 만드는가?

도움이 되었습니까?

해결책

iOS 3.0 이상

iPhone OS 3.0 이상 cornerRadius 에 속성 CALayer 수업. 모든 견해에는 다음과 같습니다 CALayer 조작 할 수있는 인스턴스. 즉, 한 줄로 둥근 모서리를 얻을 수 있습니다.

view.layer.cornerRadius = 8;

당신은 필요합니다 #import <QuartzCore/QuartzCore.h> 그리고 Calayer의 헤더 및 속성에 액세스하려면 Quartzcore 프레임 워크에 연결됩니다.

iOS 3.0 이전

내가 최근에 사용했던 한 가지 방법은 단순히 둥근 사각형을 그리는 Uiview 서브 클래스를 만들고 Uilabel 또는 내 경우 UitextView를 그 내부의 하위 뷰로 만드는 것입니다. 구체적으로:

  1. a UIView 서브 클래스와 같은 이름을 지정하십시오 RoundRectView.
  2. ~ 안에 RoundRectView'에스 drawRect: 메소드, 가장자리의 CGContextAdDlinEtoPoint ()와 같은 코어 그래픽 호출 및 둥근 모서리의 CGContextAdDarcTopoint ()와 같은 코어 그래픽 호출을 사용하여 뷰의 경로를 그립니다.
  3. a UILabel 인스턴스 및 RoundRectView의 하위 뷰로 만드십시오.
  4. 라벨의 프레임을 RoundRectView의 한계의 몇 픽셀 삽입으로 설정하십시오. (예를 들어, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

일반적인 uiview를 작성한 다음 검사관을 사용하여 클래스를 변경하는 경우 인터페이스 빌더를 사용하여 RoundRectView를 뷰에 배치 할 수 있습니다. 앱을 컴파일하고 실행할 때까지 사각형이 표시되지 않지만 적어도 하위 뷰를 배치하여 필요한 경우 매장 또는 작업에 연결할 수 있습니다.

다른 팁

iOS 7.1 이상인 장치의 경우 다음을 추가해야합니다.

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;

Oscarswyck를 기반으로 신속한 iOS8 이후에 : 답변 :

yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
  1. 당신은 있습니다 UILabel 라고 불리는: myLabel.
  2. "M"또는 "H"파일 가져 오기 : #import <QuartzCore/QuartzCore.h>
  3. 당신의 viewDidLoad 이 줄을 쓰십시오 : self.myLabel.layer.cornerRadius = 8;

    • CornerRadius 값을 8에서 다른 숫자로 변경할 수있는 방법에 따라 다릅니다. :)

행운을 빕니다

이러한 방식으로 컨트롤의 경계 너비로 둥근 테두리를 만들 수 있습니다.

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


그냥 교체하십시오 lblName 당신과 함께 UILabel.

메모:- 가져 오는 것을 잊지 마십시오 <QuartzCore/QuartzCore.h>

또 다른 방법은 PNG를 uilabel 뒤에 배치하는 것입니다. 개별 레이블에 대한 모든 아트 워크가있는 단일 배경 PNG를 오버레이하는 여러 레이블이있는 뷰가 있습니다.

Xcode 7.3.1 iOS 9.3.2

 _siteLabel.layer.masksToBounds = true;
  _siteLabel.layer.cornerRadius = 8;

나는 신속하게 만들었다 UILabel 이 효과를 달성하기위한 서브 클래스. 또한 최대 대비를 위해 텍스트 색상을 검은 색 또는 흰색으로 자동으로 설정합니다.

결과

colors-rounded-borders

사용 된 소스 포스트 :

운동장

이것을 iOS 놀이터에 붙여 넣기 만하면됩니다.

//: 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())
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    label.text = @"Your String.";
    label.layer.cornerRadius = 8.0;
    [self.view addSubview:label];

UI 객체의 둥근 코너를 원한다면 (UILabel, UIView, UIButton, UIImageView) 스토리 보드로 설정합니다 clip to bounds 진실하고 세트 User Defined Runtime Attributes 핵심 경로layer.cornerRadius, type = 숫자 및 값 = 9 (요구 사항으로)

Set clip to bounds as Set User Defined Runtime Attributes as

monotouch / xamarin.ios에서 나는 다음과 같은 문제를 해결했습니다.

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;

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

    }

당신은 사용해 보셨습니까? UIButton 인터페이스 빌더 (둥근 모서리가 있음)에서 레이블처럼 보이도록 설정을 실험합니다. 당신이 원하는 것은 내부에 정적 텍스트를 표시하는 것입니다.

스위프트 3

배경색으로 둥근 레이블을 원한다면 대부분의 다른 답변 외에도 설정해야합니다. layer의 배경색도. 설정시 작동하지 않습니다 view 배경색.

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

자동 레이아웃을 사용하는 경우 라벨 주위에 패딩을 원하고 레이블의 크기를 수동으로 설정하지 않으려면 uilabel 서브 클래스를 만들고 재정의 할 수 있습니다. intrinsincContentSize 재산:

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

두 가지를 결합하려면 설정해야합니다. label.textAlignment = center, 그렇지 않으면 텍스트가 정렬됩니다.

2017 년 8 월에 테스트 된 Swift 3에서 Xcode 8.1.2에서 잘 작동합니다.

"CornerRadius"는 둥근 가장자리를 설정하는 핵심 속성입니다. 응용 프로그램의 모든 레이블에 동일한 스타일을 사용하는 경우 확장 방법을 권장합니다.

암호:

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

산출:

enter image description here

왜 확장 방법인가?

신속한 파일을 만들고 다음 코드를 추가하십시오. 다음 코드는 "uilabel"클래스에 확장 메소드가있는 다음 코드를 추가합니다. 여기서이 방법은 사용자 정의이지만 응용 프로그램의 모든 레이블에 대해 작동하며 일관성과 클린 코드를 유지하는 데 도움이됩니다. 향후 스타일을 변경하면 확장 방법에서만 필요합니다.

정확히 무엇을하고 있는지에 따라 이미지를 만들어 프로그래밍 방식으로 배경으로 설정할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top