0

这是我为自定义UIView类制作的以下代码,您可以在界面构建器中控制它的阴影:

#import "ShadowView.h"

@interface ShadowView ()

@property (copy, nonatomic) IBInspectable UIColor *shadowColor;
@property (assign, nonatomic) IBInspectable CGFloat xOffset;
@property (assign, nonatomic) IBInspectable CGFloat yOffset;
@property (assign, nonatomic) IBInspectable float shadowOpacity;
@property (assign, nonatomic) IBInspectable CGFloat shadowRadius;
@property (assign, nonatomic) IBInspectable CGFloat xInset;
@property (assign, nonatomic) IBInspectable CGFloat yInset;

@end

@implementation ShadowView

#pragma mark - Lifecycle

//-(void)awakeFromNib {
//    [super awakeFromNib];
//    [self setUpView];
//}

-(void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self setUpView];
}

#pragma mark - Helpers

-(void)setUpView {
    self.layer.shadowColor = _shadowColor.CGColor;
    self.layer.shadowOffset = CGSizeMake(_xOffset, _yOffset);
    self.layer.shadowOpacity = _shadowOpacity;
    self.layer.shadowRadius = _shadowRadius;
    CGRect shadowRect = CGRectInset(self.bounds, _xInset, _yInset);
    self.layer.shadowPath = [[UIBezierPath bezierPathWithRect:shadowRect] CGPath];
}

@end

当我使用awakeFromNib时,阴影在 iPhone 5 模拟器上工作,但只有一半在 iPhone6 模拟器上工作。drawRect似乎对所有人都有效,但我见过使用init(frame: CGRect)and的 Swift 示例init?(coder aDecoder: NSCoder)。我需要什么方法才能一直做到这一点?

注意:我没有IB_DESIGNABLE在这种情况下使用,因为阴影不会在界面生成器中呈现。

4

1 回答 1

0

使用 IBInspectable 时,不需要添加 -(void)setupview 方法来设置所有属性。您必须添加单独的 setter 方法,如下所示:例如

-(void)setShadowColor:(UIColor)color {
     _shadowColor = color;
     self.layer.shadowColor = _shadowColor.CGColor;
}
........

希望它可以帮助你。

于 2016-09-23T03:11:11.910 回答