UIButton에서 테두리를 만드는 방법은 무엇입니까?


답변:


352

버튼의 레이어 속성에 액세스하여 CALayer에서 테두리 속성을 설정할 수 있습니다.

먼저 Quartz를 추가하십시오

#import <QuartzCore/QuartzCore.h>

속성 설정 :

myButton.layer.borderWidth = 2.0f;
myButton.layer.borderColor = [UIColor greenColor].CGColor;

보다:

https://developer.apple.com/documentation/quartzcore/calayer#//apple_ref/occ/cl/CALayer

위 링크의 CALayer를 사용하면 모서리 반경, maskToBounds 등과 같은 다른 속성을 설정할 수 있습니다.

또한 버튼 재미에 대한 좋은 기사 :

https://web.archive.org/web/20161221132308/http://www.apptite.be/tutorial_custom_uibuttons.php


3
대상 편집기의 빌드 단계 탭에서 대상을 QuartCore 프레임 워크에 연결해야합니다.
zekel

1
석영을 가져와야합니까? 버튼 없이도 레이어에 액세스 할 수 있습니다. 묻는 나의 목적은 : Quartz를 가져올 때 우리가 얻는 이점은 무엇입니까
Alix

1
CGColor
Anurag Sharma

51

매우 간단합니다. 파일에 quartzCore 헤더를 추가하십시오 (프로젝트에 쿼츠 프레임 워크를 추가해야합니다)

그리고이 작업을 수행

[[button layer] setCornerRadius:8.0f];

[[button layer] setMasksToBounds:YES];

[[button layer] setBorderWidth:1.0f];

필요에 따라 float 값을 변경할 수 있습니다.

즐겨.


전형적인 현대 코드는 다음과 같습니다.

self.buttonTag.layer.borderWidth = 1.0f;
self.buttonCancel.layer.borderWidth = 1.0f;

self.buttonTag.layer.borderColor = [UIColor blueColor].CGColor;
self.buttonCancel.layer.borderColor = [UIColor blueColor].CGColor;

self.buttonTag.layer.cornerRadius = 4.0f;
self.buttonCancel.layer.cornerRadius = 4.0f;

그것은 세그먼트 컨트롤과 비슷한 모습입니다.

스위프트 업데이트 :

  • "QuartzCore"를 추가 할 필요가 없습니다

그냥 해:

button.layer.cornerRadius = 8.0
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.black.cgColor

23

그리고 신속하게 "QuartzCore / QuartzCore.h"를 가져올 필요가 없습니다.

그냥 사용하십시오 :

button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor

또는

button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor

XCode 9에 따르면 "CGColor는 cgColor로 이름이 바뀌 었습니다".
BlenderBender

20

레이어를 설정 문제는의 borderWidthborderColor 당신이 버튼을 터치 할 때 경계가 하이라이트 효과를 애니메이션하지 않습니다.

물론 버튼의 이벤트를 관찰하고 그에 따라 테두리 색상을 변경할 수 있지만 불필요한 느낌입니다.

또 다른 옵션은 확장 가능한 UIImage를 만들어 버튼의 배경 이미지로 설정하는 것입니다. 다음과 같이 Images.xcassets에서 이미지 세트를 만들 수 있습니다.

Images.xcassets

그런 다음 버튼의 배경 이미지로 설정합니다.

버튼 속성

이미지가 템플릿 이미지 인 경우 버튼의 색조 색상을 설정할 수 있으며 테두리가 변경됩니다.

최종 버튼

이제 터치하면 나머지 버튼으로 테두리가 강조 표시됩니다.


이미지를 무엇으로 만드나요?
Bigfoot11

1
그 이미지를 스케치하기 위해 사용했지만 Gimp, Illustrator, Photoshop을 사용할 수 있습니다.
juanjo

좋은 대답입니다. 레이어를 변경하는 것보다 낫습니다 borderWidth.
Alexander Doloz

8

반경, 색상 및 너비 버튼을 변경하려면 다음과 같이 설정하십시오.

self.myBtn.layer.cornerRadius = 10;
self.myBtn.layer.borderWidth = 1;
self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;

8

Ben Packard의 답변 에서 업데이트 된 버전 ( Swift 3.0.1 )이 있습니다 .

import UIKit

@IBDesignable class BorderedButton: UIButton {

    @IBInspectable var borderColor: UIColor? {
        didSet {
            if let bColor = borderColor {
                self.layer.borderColor = bColor.cgColor
            }
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }

    override var isHighlighted: Bool {
        didSet {
            guard let currentBorderColor = borderColor else {
                return
            }

            let fadedColor = currentBorderColor.withAlphaComponent(0.2).cgColor

            if isHighlighted {
                layer.borderColor = fadedColor
            } else {

                self.layer.borderColor = currentBorderColor.cgColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = currentBorderColor.cgColor
                animation.duration = 0.4
                self.layer.add(animation, forKey: "")
            }
        }
    }
}

그 결과 버튼을 스토리 보드 덕분에 내부에 사용할 수 있습니다 @IBDesignable@IBInspectable태그입니다.

여기에 이미지 설명을 입력하십시오

또한 정의 된 두 가지 속성을 사용하면 인터페이스 빌더에서 직접 테두리 너비와 색상을 설정하고 결과를 미리 볼 수 있습니다.

여기에 이미지 설명을 입력하십시오

테두리 반경 및 하이라이트 페이딩 시간에 대해서도 비슷한 방식으로 다른 속성을 추가 할 수 있습니다.


나는 스위프트 4에 대한 제약에 문제가 있었고, 풀 사이즈 버튼 (폭에서 좌우로)을했다 .xcode에서 테두리 미리보기를 매우 잘 보았지만 에뮬레이터 또는 장치를 통해 테두리가 버튼 내부의 텍스트, 내가 추가 한 유일한 자동 레이아웃 제약 조건은 가로 중앙에 있었지만 어떻게 수정합니까? 감사!
Cristian Chaparro A.

@CristianChaparroA. 그 이유는 prepareForInterfaceBuilder앱을 실행할 때가 아니라 IB에서만 호출되기 때문입니다 . 따라서 UIEdgeInsets도 설정 awakeFromNib하면 앱을 실행할 때도 표시됩니다.
사무엘

6

가져올 필요가 없습니다 QuartzCore.h지금 . iOS 8 SDK 및 Xcode 6.1을 참조하십시오.

직접 사용 :

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

6

다음은 UIButton이미지를 사용하지 않고 강조 표시된 상태 애니메이션을 지원 하는 서브 클래스입니다. 또한보기의 색조 모드가 변경 될 때 테두리 색상을 업데이트합니다.

class BorderedButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = tintColor.CGColor
        layer.borderWidth = 1
        layer.cornerRadius = 5

        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        layer.borderColor = tintColor.CGColor
    }

    override var highlighted: Bool {
        didSet {
            let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor

            if highlighted {
                layer.borderColor = fadedColor
            } else {
                layer.borderColor = tintColor.CGColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = tintColor.CGColor
                animation.duration = 0.4
                layer.addAnimation(animation, forKey: "")
            }
        }
    }
}

용법:

let button = BorderedButton(style: .System) //style .System is important

외관:

여기에 이미지 설명을 입력하십시오

여기에 이미지 설명을 입력하십시오


6

이것은 Swift 3.0 Worked on 최신 버전 August-2017에서 다양한 방법으로 달성 할 수 있습니다

옵션 1:

UI 버튼에 borderWidth 속성 값을 직접 할당하십시오 :

  btnUserButtonName.layer.borderWidth = 1.0

UI 버튼의 기본 색상 값으로 제목을 설정하십시오.

btnUserButtonName.setTitleColor(UIColor.darkGray, for: .normal)

UI 버튼의 테두리 속성 값에 테두리를 기본 색상으로 설정하십시오.

btnUserButtonName.layer.borderColor = UIColor.red

UI 버튼의 테두리 속성 값에 대한 사용자 정의 색상을 설정하십시오.

   let myGrayColor = UIColor(red: 0.889415, green: 0.889436, blue:0.889424, alpha: 1.0 )
   btnUserButtonName.layer.borderColor = myGrayColor.cgColor

옵션 2 : [권장]

Extension 메서드를 사용하면 응용 프로그램 전체의 Button이 일관되게 보이고 모든 위치에서 여러 줄의 코드를 반복 할 필요가 없습니다.

//Create an extension class in any of the swift file

extension UIButton {
func setBordersSettings() {
        let c1GreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.layer.borderColor = c1GreenColor.cgColor
        self.setTitleColor(c1GreenColor, for: .normal)
        self.layer.masksToBounds = true
    }
}

코드 사용법 :

//use the method and call whever the border has to be applied

btnUserButtonName.setBordersSettings()

확장 방법 버튼 출력 :

여기에 이미지 설명을 입력하십시오


2

Swift 3으로 업데이트

    button.layer.borderWidth = 0.8
    button.layer.borderColor = UIColor.blue.cgColor

여기에 이미지 설명을 입력하십시오


2

스위프트 3에서 *****

테두리를 만들려면

 btnName.layer.borderWidth = 1
 btnName.layer.borderColor = UIColor.black.cgColor

모서리를 둥글게하려면

 btnName.layer.cornerRadius = 5

1

스위프트 5

button.layer.borderWidth = 2

테두리의 색상을 변경하려면

button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)

1
button.layer.borderColor = UIColor.gray.cgColor도 허용됩니다!
카를로스 이라노
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.