English 中文(简体)
目标C: 当UIButton受到压力时,帮助改变背景。
原标题:Objective C - Help with changing background color when UIButton is pressed

我是新到来的,而且我会得到任何帮助。 我试图改变一个顿的背景,一旦它受到压力。 我尝试了草场歌剧,但没有成功。 我确信这不符合UIButton。 是否有方案方式完成这项任务? 欢迎所有想法和建议。

最佳回答

I woudl suggest creating a simple image that contains the background color you want and setting that via the existing methods in the UIButton. (check Wrights Answer for the doc link).

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString* fileLocation = [[NSBundle mainBundle] pathForResource:@"buttonBG" ofType:@"png"];
UIImage* bgImage = [UIImage imageWithContentsOfFile:fileLocation];
if (bgImage != nil) { // check if the image was actually set
  [button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
} else {
  NSLog(@"Error trying to read the background image");
}

这应当做到。 也许可以找到更好的办法,在飞行中创造必要的形象,但这却使Im不是公司。

[edit: a bit more verbose code ]

问题回答

假设你拥有一个未加工的习俗,在普通状态中拥有“关于”的名称:

- (IBAction) toggleButtonState {
    if ([toggleButton titleForState:UIControlStateNormal] == @"On") {
        [toggleButton setTitle: @"Off" forState:UIControlStateNormal];
        [toggleButton setBackgroundColor:[UIColor redColor]];
    }
    else {
        [toggleButton setTitle: @"On" forState:UIControlStateNormal];
        [toggleButton setBackgroundColor:[UIColor greenColor]];

    }
}

所有其他的县都有一个形象,在观点面前,因此,如果图象完全填满,则大多数座标都会发生变化。

我也建议使用图像,但为了学习目的,这将发挥作用。

Ive刚刚出现同样的问题,最后利用UIButton子级处理这一问题。 我只使用梯度,因为如果你不需要,你就能够简单地清除梯度,它就会看得更好。 我解释了我所使用的程序,并列入了该员额底部的全部代码。

  • 首先,增加各层的特性。 我为基梯梯梯度建立了两层,为增加小幅风格创造了一层。

     @interface gradientButton()
     @property (nonatomic, strong) CAGradientLayer* gradientLayer;
     @property (nonatomic, strong) CAGradientLayer* glossyLayer;
     @end
    
  • Then either in -(void)awakeFromNib or in -(id)initWithFrame:(CGRect)frame ,depending on if you will load from storyboard or code respectively, configure the gradients and add the layers, round your corners off and customize the font highlight color.

     -(void)awakeFromNib
     {
         _gradientLayer = [[CAGradientLayer alloc] init];
         _gradientLayer.bounds = self.bounds;
         _gradientLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
         [self.layer insertSublayer:_gradientLayer atIndex:0];
    
        self.layer.cornerRadius = 5.0f; 
        self.layer.masksToBounds = YES;
        self.layer.borderWidth = 1.0f;
    
        _glossyLayer = [[CAGradientLayer alloc] init];
        _glossyLayer.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height/2);
        _glossyLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/4);
        [self.layer addSublayer:_glossyLayer];
    
         [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         [self setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
    
     }
    
  • 其次,压倒性<代码>-(避免)drawRect(CGRect)rect,以适用你的层次和界定其肤色。

     #define GRADIENT_TOP [UIColor colorWithRed:38.0/255.0 green:78.0/255.0 blue:54.0/255.0 alpha:1]
     #define GRADIENT_BOTTOM [UIColor colorWithRed:44.0/255.0 green:71.0/255.0 blue:56.0/255.0 alpha:1]
     #define GLOSS_TOP [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.95f]
     #define GLOSS_BOTTOM [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.35f]
     #define GRADIENT_SELECTED_TOP [UIColor colorWithRed:138.0/255.0 green:178.0/255.0 blue:154.0/255.0 alpha:1]
     #define GRADIENT_SELECTED_BOTTOM [UIColor colorWithRed:114.0/255.0 green:171.0/255.0 blue:156.0/255.0 alpha:1]
    
    
    
     - (void)drawRect:(CGRect)rect
     {
    
         [_gradientLayer setColors:@[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
    
         [_glossyLayer setColors:@[(id)[GLOSS_TOP CGColor], (id)[GLOSS_BOTTOM CGColor]]];
         [super drawRect:rect];
     }
    
  • Finally, and the bit we ve all been waiting for, override -(void)setHighlighted:(BOOL)highlighted{ so we can apply the highlight effect were looking for.

     -(void)setHighlighted:(BOOL)highlighted{
         [super setHighlighted:highlighted];
         if(highlighted)
             [_gradientLayer setColors:@[(id)[GRADIENT_SELECTED_TOP CGColor],(id)[GRADIENT_SELECTED_BOTTOM CGColor]]];
         else
             [_gradientLayer setColors:@[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
     }
    
  • 在那里,我们现在刚刚摆脱了UIButton的改变阶级和你的好坏。 http://pastebin.com

I have created a subclass which get background color and creates an UIImage for each state. For me it s more useful a subclass instead a category, so that s up to you.

@implementation ROCRoundColorButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        UIColor *darkColor;
        darkColor = [self darkColorFromBackgroundColor];

        [self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
       [self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{

   self = [super initWithCoder:aDecoder];
   if (self) {

       UIColor *darkColor;
       darkColor = [self darkColorFromBackgroundColor];

       [self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
       [self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
   }
   return self;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
  - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
*/

#pragma mark -
#pragma mark Private methods

- (UIColor *)darkColorFromBackgroundColor
{
const float* components = CGColorGetComponents( self.backgroundColor.CGColor );
CGFloat red     = components[0];
CGFloat green = components[1];
CGFloat blue   = components[2];
CGFloat alpha = components[3];
if (red > 0) {
    red -= 0.1;
}
if (green > 0) {
    green -= 0.1;
}
if (blue > 0) {
    blue -= 0.1;
}
UIColor *darkColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
return darkColor;
}

- (UIImage *)imageWithColor:(UIColor *)color withSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [color CGColor]);
//CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:5];
[roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];
[color setFill]; 

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

return image;
}

事实上,你可以在故事片板上使用这个词,改变这个类别,并从中确定背景。





相关问题
Asynchronous request to the server from background thread

I ve got the problem when I tried to do asynchronous requests to server from background thread. I ve never got results of those requests. Simple example which shows the problem: @protocol ...

objective-c: Calling a void function from another controller

i have a void, like -(void) doSomething in a specific controller. i can call it in this controller via [self doSomething], but i don t know how to call this void from another .m file. I want to call ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

NSUndoManager and runModalForWindow:

I have a simple Core Data app which displays a list of entities in the main window. To create or add new entities, I use a second modal window with a separate managed object context so changes can be ...

NSMutableArray values becoming "invalid"

I m trying to show a database information in a tableview and then the detailed information in a view my problem is as follow: I created a NSMutableArray: NSMutableArray *myArray = [[NSMutableArray ...

iPhone numberpad with decimal point

I am writing an iPhone application which requires the user to enter several values that may contain a decimal point (currency values, percentages etc.). The number of decimal places in the values ...

热门标签