IT

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

lottoking 2020. 5. 25. 22:20
반응형

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


내 앱에서 "addButton"이라는 사용자 정의 버튼을 사용하고 흰색으로 테두리를 만들고 싶습니다. 사용자 정의 버튼 주위에 흰색 테두리를 얻으려면 어떻게해야합니까?


버튼의 레이어 속성에 액세스하여 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


매우 간단합니다. 파일에 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

그리고 신속하게 "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

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

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

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

Images.xcassets

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

버튼 속성

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

최종 버튼

Now the border will highlight with the rest of the button when touched.


To change button Radius, Color and Width I set like this:

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;

You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

Directly use:

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

Here's an updated version (Swift 3.0.1) from Ben Packard's answer.

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: "")
            }
        }
    }
}

The resulting button can be used inside your StoryBoard thanks to the @IBDesignable and @IBInspectable tags.

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

Also the two properties defined, allow you to set the border width and color directly on interface builder and preview the result.

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

Other properties could be added in a similar fashion, for border radius and highlight fading time.


Here's a UIButton subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

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: "")
            }
        }
    }
}

Usage:

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

Appearance:

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

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


This can be achieved in various methods in Swift 3.0 Worked on Latest version August - 2017

Option 1:

Directly assign the borderWidth property values for UI Button:

  btnUserButtonName.layer.borderWidth = 1.0

Set Title with Default Color values for UI Button:

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

Set Border with Default Color for the border property values for UI Button:

btnUserButtonName.layer.borderColor = UIColor.red

Set user defined Color for the border property values for UI Button:

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

Option 2: [Recommended]

Use the Extension method, so the Button through out the application will be looking consistent and no need to repeat multiple lines of code every where.

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

Usage in code:

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

btnUserButtonName.setBordersSettings()

Output of Extension method Button:

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


Update with Swift 3

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

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


****In Swift 3****

To create border

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

To make corner rounded

 btnName.layer.cornerRadius = 5

참고 URL : https://stackoverflow.com/questions/8162411/how-to-create-border-in-uibutton

반응형