sourcecode

강조 표시된 상태에서 UI 단추의 배경색을 변경하는 방법은 무엇입니까?

copyscript 2023. 5. 9. 22:56
반응형

강조 표시된 상태에서 UI 단추의 배경색을 변경하는 방법은 무엇입니까?

앱에서 강조 표시된 부분이 있습니다.UIButton(예를 들어 사용자가 버튼에 손가락을 갖다 댄 경우) 버튼이 강조 표시된 상태에서 배경색을 변경해야 합니다.

다음을 시도했습니다.

_button.backgroundColor = [UIColor redColor];

하지만 효과가 없습니다.색상은 동일하게 유지됩니다.버튼이 강조 표시되지 않고 정상적으로 작동할 때 동일한 코드를 시도했습니다.전화도 해봤습니다.-setNeedsDisplay색깔을 바꾼 후에는 아무런 효과가 없었습니다.

버튼을 강제로 배경색을 변경하는 방법은 무엇입니까?

오버라이드할 수 있습니다.UIButtonsetHighlighted방법.

목표-C

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (highlighted) {
        self.backgroundColor = UIColorFromRGB(0x387038);
    } else {
        self.backgroundColor = UIColorFromRGB(0x5bb75b);
    }
}

Swift 3.0 및 Swift 4.1

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.black : UIColor.white
    }
}

이것이 당신이 추구하는 것을 해결할 수 있는지 아니면 당신의 일반적인 개발 환경에 맞는지는 잘 모르겠지만, 우선 터치다운 이벤트에서 버튼의 배경색을 변경하는 것이 좋습니다.

옵션 1:

캡처하려면 UIControlEvent라는 두 이벤트가 필요합니다.TouchDown은 사용자가 버튼을 누를 때 사용합니다.UI 컨트롤 이벤트터치업 인사이드 및 UI 컨트롤 이벤트TouchUpOutside는 정상 상태로 되돌리기 위해 버튼을 놓을 때 사용됩니다.

UIButton *myButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];
[myButton setBackgroundColor:[UIColor blueColor]];
[myButton setTitle:@"click me:" forState:UIControlStateNormal];
[myButton setTitle:@"changed" forState:UIControlStateHighlighted];
[myButton addTarget:self action:@selector(buttonHighlight:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];

옵션 2:

원하는 하이라이트 색상으로 만든 이미지를 반환합니다.이것은 범주일 수도 있습니다.

+ (UIImage *)imageWithColor:(UIColor *)color {
   CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
   UIGraphicsBeginImageContext(rect.size);
   CGContextRef context = UIGraphicsGetCurrentContext();

   CGContextSetFillColorWithColor(context, [color CGColor]);
   CGContextFillRect(context, rect);

   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return image;
}

버튼의 강조 표시된 상태를 변경합니다.

[myButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];

오버라이드할 필요가 없습니다.highlighted계산된 재산으로서.속성 관찰자를 사용하여 배경색 변경을 트리거할 수 있습니다.

override var highlighted: Bool {
    didSet {
        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
    }
}

스위프트 4

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white
    }
}

Swift의 편리한 일반 확장 기능:

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color), forState: state)
    }
}

스위프트 3.0

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context?.setFillColor(color.cgColor)
        context?.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color: color), for: state)
    }
}

Swift에서는 setHighlighted 메서드를 재정의하지 않고 강조 표시된(또는 선택된) 속성의 액세스자를 재정의할 수 있습니다.

override var highlighted: Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                backgroundColor = UIColor.blackColor()
            }
            else {
                backgroundColor = UIColor.whiteColor()
            }
            super.highlighted = newValue
        }
    }

강조 표시된 변수를 재정의합니다. 추가하기@IBInspectable스토리보드에서 강조 표시된 배경색을 편집할 수 있습니다. 이 색도 멋집니다.

class BackgroundHighlightedButton: UIButton {
    @IBInspectable var highlightedBackgroundColor :UIColor?
    @IBInspectable var nonHighlightedBackgroundColor :UIColor?
    override var highlighted :Bool {
        get {
            return super.highlighted
        }
        set {
            if newValue {
                self.backgroundColor = highlightedBackgroundColor
            }
            else {
                self.backgroundColor = nonHighlightedBackgroundColor
            }
            super.highlighted = newValue
        }
    }
}

보다 콤팩트한 솔루션(@alecksejs-saliks 답변 기반):

Swift 3/4+:

override var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? .lightGray : .white
    }
}

스위프트 2:

override var highlighted: Bool {
    didSet {
        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
    }
}

재정의하지 않으려면 @timur-bernikowich의 답변(Swift 4.2)의 업데이트된 버전입니다.

extension UIButton {
  func setBackgroundColor(_ color: UIColor, forState controlState: UIControl.State) {
    let colorImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in
      color.setFill()
      UIBezierPath(rect: CGRect(x: 0, y: 0, width: 1, height: 1)).fill()
    }
    setBackgroundImage(colorImage, for: controlState)
  }
}

하위 분류 없이 Swift 3+솔루션입니다.

extension UIButton {
  func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContext(rect.size)
    color.setFill()
    UIRectFill(rect)
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(colorImage, for: state)
  }
}

이 확장 기능을 사용하면 다양한 상태의 색상을 쉽게 관리할 수 있으며 강조 표시된 색상이 제공되지 않을 경우 일반 색상이 자동으로 페이드됩니다.

button.setBackgroundColor(.red, for: .normal)

Swift 3+ 구문을 사용하는 UIButton 확장:

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.setBackgroundImage(colorImage, for: forState)
    }}

다음과 같이 사용:

YourButton.setBackgroundColor(color: UIColor.white, forState: .highlighted)

원답: https://stackoverflow.com/a/30604658/3659227

다음은 Swift에서 UIButton 확장을 사용하여 강조 표시된 BackgroundColor라고 하는 IBInspectable을 추가하는 방법입니다.하위 클래스가 필요 없는 하위 클래스와 유사합니다.

private var HighlightedBackgroundColorKey = 0
private var NormalBackgroundColorKey = 0

extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &HighlightedBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &HighlightedBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private var normalBackgroundColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &NormalBackgroundColorKey) as? UIColor
        }

        set(newValue) {
            objc_setAssociatedObject(self,
                &NormalBackgroundColorKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    override public var backgroundColor: UIColor? {
        didSet {
            if !highlighted {
                normalBackgroundColor = backgroundColor
            }
        }
    }

    override public var highlighted: Bool {
        didSet {
            if let highlightedBackgroundColor = self.highlightedBackgroundColor {
                if highlighted {
                    backgroundColor = highlightedBackgroundColor
                } else {
                    backgroundColor = normalBackgroundColor
                }
            }
        }
    }
}

이것이 도움이 되길 바랍니다.

이 범주를 사용하여 BackgroundColor:forState: 메서드 집합을 추가할 수 있습니다.

https://github.com/damienromito/UIButton-setBackgroundColor-forState-

세부 사항

  • Xcode 11.1(11A1027), Swift 5

해결책

import UIKit

extension UIColor {
    func createOnePixelImage() -> UIImage? {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.setFillColor(cgColor)
        context.fill(CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIButton {
    func setBackground(_ color: UIColor, for state: UIControl.State) {
        setBackgroundImage(color.createOnePixelImage(), for: state)
    }
}

사용.

button.setBackground(.green, for: .normal)

이거 먹어봐요!!

TouchDown Event set One(터치다운 이벤트 세트)의 경우 색 하나를 설정하고 TouchUpInside(터치업 내부)의 경우 색 하나를 설정합니다.

- (IBAction)touchedDown:(id)sender {
    NSLog(@"Touched Down");
    btn1.backgroundColor=[UIColor redColor];
}

- (IBAction)touchUpInside:(id)sender {
    NSLog(@"TouchUpInside");
    btn1.backgroundColor=[UIColor whiteColor];    
}
extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect(origin: CGPoint.zero, size: size))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        setBackgroundImage(colorImage, for: forState)
    }

}

스위프트 5, 감사합니다 @Maverick.

업데이트:

UIButton BackgroundColor Swift 라이브러리를 사용합니다.

이전 버전:

아래 도움말을 사용하여 그레이스케일 채우기 색으로 1pxx1px 이미지를 만듭니다.

UIImage *image = ACUTilingImageGray(248/255.0, 1);

또는 RGB 채우기 색:

UIImage *image = ACUTilingImageRGB(253/255.0, 123/255.0, 43/255.0, 1);

그럼, 그것을 사용하세요.image버튼의 배경 이미지를 설정하려면:

[button setBackgroundImage:image forState:UIControlStateNormal];

도우미

#pragma mark - Helpers

UIImage *ACUTilingImageGray(CGFloat gray, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetGrayFillColor(context, gray, alpha);
    });
}

UIImage *ACUTilingImageRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetRGBFillColor(context, red, green, blue, alpha);
    });
}

UIImage *ACUTilingImage(CGFloat alpha, void (^setFillColor)(CGContextRef context))
{
    CGRect rect = CGRectMake(0, 0, 0.5, 0.5);
    UIGraphicsBeginImageContextWithOptions(rect.size, alpha == 1, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    setFillColor(context);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

참고:ACU는 Acani Utilities라는 내 코코아 터치 정적 라이브러리의 클래스 접두사입니다. AC는 Acani, U는 Utilities.

간단한 것은 해당 UIButton Extension만 사용하는 것입니다.

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }

}

그리고 이것을 사용합니다.

 optionButton.setBackgroundColor(color: UIColor(red:0.09, green:0.42, blue:0.82, alpha:1.0), forState: .selected)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .highlighted)

 optionButton.setBackgroundColor(color: UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0), forState: .normal)

UIButton을 하위 분류하고 편리하게 사용할 수 있도록 검사 가능한 속성을 추가합니다(Swift 3.0에서 작성).

final class SelectableBackgroundButton: UIButton {

    private struct Constants {
        static let animationDuration: NSTimeInterval = 0.1
    }

    @IBInspectable
    var animatedColorChange: Bool = true

    @IBInspectable
    var selectedBgColor: UIColor = UIColor.blackColor().colorWithAlphaComponent(0.2)

    @IBInspectable
    var normalBgColor: UIColor = UIColor.clearColor()

    override var selected: Bool {
        didSet {
            if animatedColorChange {
                UIView.animateWithDuration(Constants.animationDuration) {
                    self.backgroundColor = self.selected ? self.selectedBgColor : self.normalBgColor
                }
            } else {
                self.backgroundColor = selected ? selectedBgColor : normalBgColor
            }
        }
    }

    override var highlighted: Bool {
        didSet {
            if animatedColorChange {
                UIView.animateWithDuration(Constants.animationDuration) {
                    self.backgroundColor = self.highlighted ? self.selectedBgColor : self.normalBgColor
                }
            } else {
                self.backgroundColor = highlighted ? selectedBgColor : normalBgColor
            }
        }
    }
}

UIButton을 하위 분류하여 State에 적합하게 만들 수 있습니다.

color 버튼.h

#import <UIKit/UIKit.h>

@interface colourButton : UIButton

-(void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;

@end

color 버튼

#import "colourButton.h"

@implementation colourButton
{
    NSMutableDictionary *colours;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    // If colours does not exist
    if(!colours)
    {
        colours = [NSMutableDictionary new];  // The dictionary is used to store the colour, the key is a text version of the ENUM
        colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]] = (UIColor*)self.backgroundColor;  // Store the original background colour
    }

    return self;
}

-(void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state
{
    // If it is normal then set the standard background here
    if(state & UIControlStateNormal)
    {
        [super setBackgroundColor:backgroundColor];
    }

    // Store the background colour for that state
    colours[[NSString stringWithFormat:@"%lu", state]]= backgroundColor;
}

-(void)setHighlighted:(BOOL)highlighted
{
    // Do original Highlight
    [super setHighlighted:highlighted];

    // Highlight with new colour OR replace with orignial
    if (highlighted && colours[[NSString stringWithFormat:@"%lu", UIControlStateHighlighted]])
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateHighlighted]];
    }
    else
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]];
    }
}

-(void)setSelected:(BOOL)selected
{
    // Do original Selected
    [super setSelected:selected];

    // Select with new colour OR replace with orignial
    if (selected && colours[[NSString stringWithFormat:@"%lu", UIControlStateSelected]])
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateSelected]];
    }
    else
    {
        self.backgroundColor = colours[[NSString stringWithFormat:@"%lu", UIControlStateNormal]];
    }
}

@end

참고(이 예는 문제가 있는 것으로 알고 있으며 몇 가지 문제가 있습니다.)

각 상태의 UIColor를 저장하기 위해 NSMutableDictay를 사용했습니다. UIControlState가 좋은 직선 Int가 아니기 때문에 키에 대해 잘못된 텍스트 변환을 수행해야 합니다.그렇게 많은 개체로 배열을 시작하고 상태를 인덱스로 사용할 수 있는 경우.

이 때문에 버튼을 선택하거나 사용하지 않는 등의 문제가 있으므로 논리가 더 필요합니다.

또 다른 문제는 만약 당신이 동시에 여러 색상을 설정하려고 한다면, 나는 버튼으로 시도하지 않았지만 당신이 이것을 할 수 있다면 그것이 작동하지 않을 수도 있다는 것입니다.

 [btn setBackgroundColor:colour forState:UIControlStateSelected & UIControlStateHighlighted];

나는 이것이 StoryBoard이고, 그것은 없고, initWithFrame이라고 가정했으니 필요하다면 그것들을 추가하세요.

이미지가 있는 경우 이 작업을 수행합니다.

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

아면이 확인해보세요.showsTouchWhenHighlighted당신에겐 충분합니다.

저는 UIButton 하위 클래스인 Stabutton을 오픈 소스로 만들어 이 기능성 구멍을 메웠습니다.MIT 라이선스로 사용할 수 있습니다.iOS 7+에서 작동합니다(이전 iOS 버전에서는 테스트하지 않았습니다).

이 문제를 해결하기 위해 처리할 카테고리를 만들었습니다.backgroundColor포함된 주UIButtons:
버튼 배경색-iOS

범주를 포드로 설치할 수 있습니다.

Objective-C와 함께 사용하기 쉽습니다.

@property (nonatomic, strong) UIButton *myButton;

...

[self.myButton bbc_backgroundColorNormal:[UIColor redColor]
                 backgroundColorSelected:[UIColor blueColor]];

Swift를 사용하면 더욱 쉽게 사용할 수 있습니다.

import ButtonBackgroundColor

...

let myButton:UIButton = UIButton(type:.Custom)

myButton.bbc_backgroundColorNormal(UIColor.redColor(), backgroundColorSelected: UIColor.blueColor())

다음을 사용하여 포드를 가져오는 것이 좋습니다.

platform :ios, '8.0'
use_frameworks!

pod 'ButtonBackgroundColor', '~> 1.0'

Pod 파일에서 use_frameworks!를 사용하면 Swift 및 objective-C로 포드를 더 쉽게 사용할 수 있습니다.

중요한

저는 또한 더 많은 정보가 담긴 블로그 포스트를 작성했습니다.

class CustomButton: UIButton {

    override var isHighlighted: Bool {
        didSet {
            if (isHighlighted) {
                alpha = 0.5
            }
            else {
                alpha = 1
            }            
        }
    }

}

https://github.com/swordray/UIButtonSetBackgroundColorForState 사용

코코아 포드를 사용하여 포드 파일에 추가

pod "UIButtonSetBackgroundColorForState"

스위프트

button.setBackgroundColor(.red, forState: .highlighted)

목표-C

[button setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];

강조 표시되거나 선택된 버튼 배경색을 간단하게 변경할 수 있습니다.setBackgroundImageUIButton의 방법과 이것을 이용한 이미지 사용.UIImage(color:)이니셜라이저(예:

btn.setBackgroundImage(UIImage(color: .black), for: .highlighted)

참고:

를 사용하는 경우cornerRadius둥근 테두리 속성을 설정해야 합니다.clipsToBounds로.true따라서 선택한 배경색은 모서리 반지름 값을 예약합니다.

해라tintColor:

_button.tintColor = [UIColor redColor];

버튼 상태에 대해 선택할 Swift의 코드는 다음과 같습니다.

func imageWithColor(color:UIColor) -> UIImage {
    let rect:CGRect = CGRectMake(0.0, 0.0, 1.0, 1.0)
     UIGraphicsBeginImageContext(rect.size)
    let context:CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    return image;
}

예:

    self.button.setImage(self.imageWithColor(UIColor.blackColor()), forState: .Highlighted)

그것을 집어넣으면 당신은 가도 좋습니다.
*속성은 IB로 설정 가능하며 강조표시된 배경이 설정되지 않은 경우 눌러도 배경이 변경되지 않습니다.

private var highlightedBackgroundColors = [UIButton:UIColor]()
private var unhighlightedBackgroundColors = [UIButton:UIColor]()
extension UIButton {

    @IBInspectable var highlightedBackgroundColor: UIColor? {
        get {
            return highlightedBackgroundColors[self]
        }

        set {
            highlightedBackgroundColors[self] = newValue
        }
    }

    override open var backgroundColor: UIColor? {
        get {
            return super.backgroundColor
        }

        set {
            unhighlightedBackgroundColors[self] = newValue
            super.backgroundColor = newValue
        }
    }

    override open var isHighlighted: Bool {
        get {
            return super.isHighlighted
        }

        set {
            if highlightedBackgroundColor != nil {
                super.backgroundColor = newValue ? highlightedBackgroundColor : unhighlightedBackgroundColors[self]
            }
            super.isHighlighted = newValue
        }
    }
}

오버라이드하지 않으려면 두 가지 작업을 설정하십시오.다운 터치업인사이드

스위프트 3:

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x:0.0,y:0.0,width: 1.0,height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context!.setFillColor(color.cgColor)
        context!.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color: color), for: state)
    }
}

아래UIIImage확장은 지정된 색상 매개 변수로 이미지 개체를 생성합니다.

extension UIImage {
    static func imageWithColor(tintColor: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        tintColor.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
       }
    }

다음과 같이 버튼 객체에 버튼 사용 예를 적용할 수 있습니다.

setupButton.setBackgroundImage(UIImage.imageWithColor(tintColor: UIColor(displayP3Red: 232/255, green: 130/255, blue: 121/255, alpha: 1.0)), for: UIControlState.highlighted)

setupButton.setBackgroundImage(UIImage.imageWithColor(tintColor: UIColor(displayP3Red: 255/255, green: 194/255, blue: 190/255, alpha: 1.0)), for: UIControlState.normal)

언급URL : https://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted

반응형