답변:
버튼의 레이어 속성에 액세스하여 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
CGColor
매우 간단합니다. 파일에 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;
그것은 세그먼트 컨트롤과 비슷한 모습입니다.
스위프트 업데이트 :
그냥 해:
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에서 이미지 세트를 만들 수 있습니다.

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

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

이제 터치하면 나머지 버튼으로 테두리가 강조 표시됩니다.
borderWidth.
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태그입니다.
또한 정의 된 두 가지 속성을 사용하면 인터페이스 빌더에서 직접 테두리 너비와 색상을 설정하고 결과를 미리 볼 수 있습니다.
테두리 반경 및 하이라이트 페이딩 시간에 대해서도 비슷한 방식으로 다른 속성을 추가 할 수 있습니다.
prepareForInterfaceBuilder앱을 실행할 때가 아니라 IB에서만 호출되기 때문입니다 . 따라서 UIEdgeInsets도 설정 awakeFromNib하면 앱을 실행할 때도 표시됩니다.
다음은 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
외관:
이것은 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()
확장 방법 버튼 출력 :