Подтвердить что ты не робот

Как добавить тень к UIButton?

Я хотел бы добавить тень к UIButton. Я попытался использовать свойства self.layer.shadow *. Эти свойства работают в UIView, но они ведут себя по-разному в UIButton. Я был бы очень признателен, если бы смог нарисовать тени. Спасибо!

self.layer.cornerRadius = 8.0f;
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;

self.layer.shadowColor = [UIColor greenColor].CGColor;
self.layer.shadowOpacity = 0.8;
self.layer.shadowRadius = 12;
self.layer.shadowOffset = CGSizeMake(12.0f, 12.0f);
4b9b3361

Ответ 1

В вопросе есть только одна крошечная ошибка, которая заставляет тень не отображаться: masksToBounds:YES также маскирует тень! Здесь правильный код:

self.layer.cornerRadius = 8.0f;
self.layer.masksToBounds = NO;
self.layer.borderWidth = 1.0f;

self.layer.shadowColor = [UIColor greenColor].CGColor;
self.layer.shadowOpacity = 0.8;
self.layer.shadowRadius = 12;
self.layer.shadowOffset = CGSizeMake(12.0f, 12.0f);

К сожалению, это означает, что мы не можем маскировать контент и иметь тень одновременно без трюков.

Помните #import <QuartzCore/QuartzCore.h>.

Ответ 2

Здесь простое решение, если вы используете UIButton:

#import <QuartzCore/QuartzCore.h>

button.imageView.layer.cornerRadius = 7.0f;
button.layer.shadowRadius = 3.0f;
button.layer.shadowColor = [UIColor blackColor].CGColor;
button.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
button.layer.shadowOpacity = 0.5f;
button.layer.masksToBounds = NO;

Просто он работал, и понял, что стоит опубликовать. Надеюсь, что это поможет!

Ответ 3

Здесь находится подкласс, который не только создает тень, но и при нажатии на кнопку анимируется.

//
//  ShadowButton.h

#import <Foundation/Foundation.h>

@interface ShadowButton : UIButton {
}

@end

//
//  ShadowButton.m

#import "ShadowButton.h"
#import <QuartzCore/QuartzCore.h>

@implementation ShadowButton

-(void)setupView{

    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOpacity = 0.5;
    self.layer.shadowRadius = 1;
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);

}

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

    return self;
}

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

    return self;
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentEdgeInsets = UIEdgeInsetsMake(1.0,1.0,-1.0,-1.0);
    self.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
    self.layer.shadowOpacity = 0.8;

    [super touchesBegan:touches withEvent:event];

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    self.contentEdgeInsets = UIEdgeInsetsMake(0.0,0.0,0.0,0.0);
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
    self.layer.shadowOpacity = 0.5;

    [super touchesEnded:touches withEvent:event];

}

@end

Ответ 4

Вы можете подклассифицировать UIButton и перезаписать метод drawRect: и вручную добавить тень. Это гораздо больше работы, и теперь вы должны сделать несколько вещей о квартете 2d, но результат - именно то, что вы хотите. В противном случае вы можете просто добавить изображение, но я предпочитаю подкласс UIButton, потому что он очень гибкий относительно размера кнопки, более общий.

Ответ 5

Вы можете создать подкласс и настроить его значения в Xcode

Ниже приведен пример:

import UIKit
import QuartzCore

@IBDesignable
class CustomButton: UIButton {

@IBInspectable var cornerRadius: CGFloat = 0 {
    didSet {
        layer.cornerRadius = cornerRadius
    }
}

@IBInspectable var borderWidth: CGFloat = 0 {
    didSet {
        layer.borderWidth = borderWidth
    }
}

@IBInspectable var borderColor: UIColor = UIColor.grayColor() {
    didSet {
        layer.borderColor = borderColor.CGColor
    }
}

@IBInspectable var shadowColor: UIColor = UIColor.grayColor() {
    didSet {
        layer.shadowColor = shadowColor.CGColor
    }
}

@IBInspectable var shadowOpacity: Float = 1.0 {
    didSet {
        layer.shadowOpacity = shadowOpacity
    }
}

@IBInspectable var shadowRadius: CGFloat = 1.0 {
    didSet {
        layer.shadowRadius = shadowRadius
    }
}

@IBInspectable var masksToBounds: Bool = true {
    didSet {
        layer.masksToBounds = masksToBounds
    }
}

@IBInspectable var shadowOffset: CGSize = CGSizeMake(12.0, 12.0) {
    didSet {
        layer.shadowOffset = shadowOffset
    }
}


 }