简体   繁体   中英

iOS7 Selected Effect on Button Border

So I am new to iOS and I want some buttons with rounded boarders. I also want those borders to have the same effect as the text within the button when the button is selected.

Since roundRect buttons are no longer an object in iOS (or at least I couldn't find it and everywhere I read said that is was no more) I decided to write a custom class that extends UIButton. This is what I have:

- (void)drawRect:(CGRect)rect{
{
   UIColor *blackColor = blackColor;
   UIColor *transBlack = [blackColor colorWithAlphaComponent:(0.5)];
   [self.layer setCornerRadius:10.0f];
   [self.layer setBorderColor:[UIColor blackColor].CGColor];
   [self.layer setBorderWidth:1.0];

   if(self.isSelected){
      [self.layer setBorderColor:(transBlack.CGColor)];
   }

I'm not sure if I am using isSelected properly. I had an NSLog under it and it never seems to be executed no matter how many times I press the buttons.

Any help and suggestions of all kinds would be greatly appreciated. Thank you.

UIButton inherit from UIView, So you can use Layer's Methods... Create new Object that Subclassing UIButton call it whatever you want, then implement the next Code: In this sample i have UIButton subclass called PressedButton in the .m file:

@implementation PressedButton


- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    //When the button is pressed the border color change to red
    self.layer.borderColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    //When the button is pressed the border color change back to black
    self.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;

}
- (void)initialize{


    self.layer.cornerRadius = 10.0f;
    self.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
    self.layer.borderWidth = 2;
    self.layer.masksToBounds = YES;


}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

@end

*** I implemented the all init methods to be sure no matter where i set the button (storyboard or via Code its get the same init).

After that just configure your button custom class to your "Pressed Button class" and that's it 在此处输入图片说明

If you need more help be free to ask :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM