这是我为自定义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
在这种情况下使用,因为阴影不会在界面生成器中呈现。