programing

UIButtons 배경색을 변경할 수 있습니까?

css3 2023. 6. 4. 22:26

UIButtons 배경색을 변경할 수 있습니까?

이것은 나를 당황하게 했습니다.

아이폰용으로 코코아에 있는 UI 버튼의 배경색을 변경하는 것이 가능합니까?배경색을 설정해 봤는데 모서리만 바뀌네요. setBackgroundColor:그런 것들에 대해 사용할 수 있는 유일한 방법인 것 같습니다.

[random setBackgroundColor:[UIColor blueColor]];
[random.titleLabel setBackgroundColor:[UIColor blueColor]];

이 작업은 복제본을 만들어 프로그래밍 방식으로 수행할 수 있습니다.

loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
[loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
loginButton.backgroundColor = [UIColor whiteColor];
loginButton.layer.borderColor = [UIColor blackColor].CGColor;
loginButton.layer.borderWidth = 0.5f;
loginButton.layer.cornerRadius = 10.0f;

편집: 물론, 당신은 해야 할 것입니다.#import <QuartzCore/QuartzCore.h>

편집: 모든 새 독서자에게 "다른 가능성"으로 추가된 몇 가지 옵션도 고려해야 합니다.참고로

이는 오래된 답변이므로 문제 해결을 위해 의견을 읽는 것이 좋습니다.

저는 다른 접근법을 가지고 있습니다.

[btFind setTitle:NSLocalizedString(@"Find", @"") forState:UIControlStateNormal];    
[btFind setBackgroundImage:[CommonUIUtility imageFromColor:[UIColor cyanColor]] 
        forState:UIControlStateNormal];
btFind.layer.cornerRadius = 8.0;
btFind.layer.masksToBounds = YES;
btFind.layer.borderColor = [UIColor lightGrayColor].CGColor;
btFind.layer.borderWidth = 1;

공통에서UI 유틸리티,

+ (UIImage *) imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //  [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

잊지 마세요#import <QuartzCore/QuartzCore.h>

UI가 있는 UI 것 .UIButtonTypeRoundedRect당신은 그것의 배경색을 변경할 수 없습니다.배경색을 변경하려고 할 때는 오히려 직사각형의 색을 변경하는 것입니다(일반적으로 선명함)그래서 두 가지 방법이 있습니다. 분류하고 UIButton을 .-drawRect:방법 또는 사용자가 다양한 버튼 상태에 대한 이미지를 만듭니다.

Interface Builder에서 배경 이미지를 설정하는 경우 IB는 버튼이 가질 수 있는 모든 상태에 대한 이미지 설정을 지원하지 않으므로 다음과 같은 코드로 이미지를 설정하는 것이 좋습니다.

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];

마지막 줄은 선택되고 강조 표시된 상태(IB에서 설정할 수 없는 상태)에 대한 이미지를 설정하는 방법을 보여줍니다.버튼을 누르면 선택한 상태가 필요하지 않은 경우 선택한 이미지(라인 4 및 6)가 필요하지 않습니다.

또 다른 가능성:

  1. 인터페이스 작성기에 UIButton을 만듭니다.
  2. '사용자 정의' 유형을 지정합니다.
  3. 이제 IB에서는 배경색을 변경할 수 있습니다.

하지만, 버튼은 사각형이고, 그것은 우리가 원하는 것이 아닙니다.이 버튼을 참조하여 IOutlet을 만들고 viewDidLoad 메서드에 다음을 추가합니다.

[buttonOutlet.layer setCornerRadius:7.0f];
[buttonOutlet.layer setClipToBounds:YES];

QuartzCore를 수입하는 것을 잊지 마세요.

하위 클래스 UIButton 및 override setHighlighted 및 setSelected 메서드

-(void) setHighlighted:(BOOL)highlighted {

  if(highlighted) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setHighlighted:highlighted];
}

-(void) setSelected:(BOOL)selected {

  if(selected) {
    self.backgroundColor = [self.mainColor darkerShade];
  } else {
    self.backgroundColor = self.mainColor;
  }
  [super setSelected:selected];
}

나의 어두운 Shade 방법은 이와 같은 UIColor 범주에 있습니다.

-(UIColor*) darkerShade {

  float red, green, blue, alpha;
  [self getRed:&red green:&green blue:&blue alpha:&alpha];

  double multiplier = 0.8f;
  return [UIColor colorWithRed:red * multiplier green:green * multiplier blue:blue*multiplier alpha:alpha];
}

컬러 UI 버튼

이미지를 사용하지 않고 Rounded Rect 스타일과 동일한 모양으로 만들려면 이 작업을 수행합니다.동일한 프레임과 자동 크기 조정 마스크를 사용하여 UIButton 위에 UIView를 배치하고 알파를 0.3으로 설정하고 배경을 색상으로 설정하기만 하면 됩니다.그런 다음 아래 스니펫을 사용하여 색상이 지정된 오버레이 보기에서 둥근 모서리를 잘라냅니다.또한 터치 이벤트가 아래의 UI 버튼까지 계단식으로 내려올 수 있도록 하려면 UI View의 IB에서 '사용자 상호 작용 활성화' 확인란의 선택을 취소합니다.

한 가지 부작용은 텍스트도 컬러화된다는 것입니다.

#import <QuartzCore/QuartzCore.h>

colorizeOverlayView.layer.cornerRadius = 10.0f;
colorizeOverlayView.layer.masksToBounds = YES;

또 다른 가능성(가장 좋고 아름다운 임호):

Interface Builder에서 필요한 배경색으로 세그먼트 2개가 있는 UIS 세그먼트 컨트롤을 만듭니다.유형을 'bar'로 설정합니다.그런 다음 세그먼트가 하나만 있는 것으로 변경합니다.인터페이스 작성기는 하나의 세그먼트를 허용하지 않으므로 프로그래밍 방식으로 이 작업을 수행해야 합니다.

따라서 이 버튼에 대한 IBOutlet을 만들고 이를 뷰의 viewDidLoad에 추가합니다.

[segmentedButton removeSegmentAtIndex:1 animated:NO];

이제 지정된 배경색을 가진 아름다운 광택이 나는 컬러 버튼이 있습니다.작업의 경우 '값이 변경됨' 이벤트를 사용합니다.

(는 이것을 http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/) 에서 찾았습니다.고마워요, 크리스!

저는 99% 확신합니다. UIButton의 배경색을 그냥 바꿀 수는 없습니다.대신에 당신은 직접 배경 이미지를 바꿔야 합니다. 제가 생각하기에 고통스럽습니다.제가 이걸 해야만 했다니 놀랍습니다.

제가 틀렸거나 배경 이미지를 설정하지 않고 더 좋은 방법이 있다면 알려주세요.

[random setBackgroundImage:[UIImage imageNamed:@"toggleoff.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];


[random setBackgroundImage:[UIImage imageNamed:@"toggleon.png"] forState:UIControlStateNormal];
    [random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

@EthanB 제안과 @karim이 뒤로 채워진 직사각형을 만드는 것에 따라, 저는 이것을 달성하기 위해 UIButton에 대한 카테고리를 만들었습니다.

카테고리 코드를 입력하십시오. https://github.com/zmonteca/UIButton-PLColor

용도:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];

주에서 사용할 옵션:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

버튼에 CAL레이어를 추가할 수도 있습니다. 색상 오버레이를 포함하여 많은 작업을 수행할 수 있습니다. 이 예에서는 일반 색상 레이어를 사용하여 색상을 쉽게 등급 조정할 수도 있습니다.추가된 레이어는 아래 레이어를 흐리지만 주의하십시오.

+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{

    CALayer *layer = button.layer;
    layer.cornerRadius = 8.0f;
    layer.masksToBounds = YES;
    layer.borderWidth = 4.0f;
    layer.opacity = .3;//
    layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;

    CAGradientLayer *colorLayer = [CAGradientLayer layer];
    colorLayer.cornerRadius = 8.0f;
    colorLayer.frame = button.layer.bounds;
    //set gradient colors
    colorLayer.colors = [NSArray arrayWithObjects:
                         (id) color.CGColor,
                         (id) color.CGColor,
                         nil];

    //set gradient locations
    colorLayer.locations = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat:0.0f],
                            [NSNumber numberWithFloat:1.0f],
                            nil];


    [button.layer addSublayer:colorLayer];

}

두번대추가에 두 합니다.UIButton위해서UIControlEventTouched그리고 변경합니다.UIButton배경색그런 다음 다시 변경합니다.UIControlEventTouchUpInside대상;

전문적이고 보기 좋은 단추의 경우 이 사용자 정의 단추 구성요소를 확인할 수 있습니다.보기 및 테이블 보기에서 직접 사용하거나 필요에 맞게 소스 코드를 수정할 수 있습니다.이게 도움이 되길 바랍니다.

이것은 하위 분류 UIButton만큼 우아하지는 않지만 빠른 것을 원한다면 - 제가 한 것은 사용자 지정 버튼을 만든 다음 버튼을 원하는 색상의 1pxxx1px 이미지를 만들고 버튼의 배경을 강조 표시된 상태로 설정하는 것입니다. - 제 요구에 적합합니다.

오래 전에 요청한 사항이고 지금은 새로운 UIButtonTypeSystem이 있습니다.그러나 새로운 질문은 이 질문의 중복으로 표시되므로 iOS 7 시스템 버튼의 맥락에서 새로운 답변을 사용합니다..tintColor소유물.

let button = UIButton(type: .System)
button.setTitle("My Button", forState: .Normal)
button.tintColor = .redColor()

[myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

이 방법으로 변경하거나 스토리보드에서 오른쪽 옵션의 배경을 변경할 수 있습니다.

스위프트 3:

        static func imageFromColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: width, height: height)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return img
        }

        let button = UIButton(type: .system)
        let image = imageFromColor(color: .red, width: 
        button.frame.size.width, height: button.frame.size.height)
        button.setBackgroundImage(image, for: .normal)

iOS 15+의 경우 Apple은 이를 위한 간단한 버튼 구성을 제공합니다.

목표-C:

randomButton.configuration = [UIButtonConfiguration filledButtonConfiguration];

스위프트:

randomButton.configuration = .filled()

언급URL : https://stackoverflow.com/questions/2808888/is-it-possible-to-change-a-uibuttons-background-color