我在将自定义 UIColor 传递给我创建的方法时遇到了麻烦。
基本上,我有一个扩展 UIButton 类的类,我可以在其中为类的不同的、通常修改的属性分配我想要的任何颜色。为此,我经常需要将事物的颜色设置为“uiColorParameter.CGColor”或“uiColorParameter”。我的问题是,当我传递自定义颜色作为参数时(因此,而不是 [UIColor whiteColor](例如),我执行 [UIColor colorWithRed:...],应用程序崩溃并显示错误“Thread 1: EXC_BAD_ACCESS (code= 1,地址=0x20)”。
该类在视图控制器中使用了 2 次。
[_beginButton updateButtonBorderWithCornerRadius:10 borderWidth:2.75 borderColor:[RoundedButton appRedColor]];
[_beginButton setEventEffectsWithColor:[UIColor redColor] secondColor:[RoundedButton appRedColor]];
在自定义类 H
@property (assign) UIColor *pColor;
@property (assign) UIColor *sColor;
在自定义类中
- (void)updateButtonBorderWithCornerRadius:(CGFloat)bRadius borderWidth:(CGFloat)bWidth borderColor:(UIColor *)bColor
{
self.layer.cornerRadius = bRadius;
self.layer.borderWidth = bWidth;
self.layer.borderColor = bColor.CGColor;
}
- (void)setEventEffectsWithColor:(UIColor *)fColor secondColor:(UIColor *)sColor
{
[self setPrimaryBorderColor:fColor];
[self setSecondaryBorderColor:sColor];
[self addTarget:self action:@selector(highlight) forControlEvents:UIControlEventTouchDown];
[self addTarget:self action:@selector(unhighlight) forControlEvents:UIControlEventTouchUpInside];
[self addTarget:self action:@selector(unhighlight) forControlEvents:UIControlEventTouchDragExit];
}
- (void)highlight
{
self.layer.borderColor = pColor.CGColor;
self.titleLabel.textColor = pColor;
}
- (void)unhighlight
{
self.layer.borderColor = sColor.CGColor; //Where the error occurs
self.titleLabel.textColor = sColor;
}
- (void)setPrimaryBorderColor:(UIColor *)color
{
pColor = color;
}
- (void)setSecondaryBorderColor:(UIColor *)color
{
sColor = color;
}
+ (UIColor *)appRedColor
{
return [UIColor colorWithRed:0.68 green:0.14 blue:0.09 alpha:1];
}
第一种方法“updateButtonBorder...”完全正常,没有错误。但是,对于第二种方法,无论您如何通过自定义 UIColor(无论是类变量,如我所做的,还是作为文字 [UIColor colorWithRed:...),它都会崩溃。但是,如果我发送一个普通的 [UIColor whiteColor],例如,它会工作得很好......
由于您的pColor
和sColor
属性被声明为assign
而不是 ,您遇到了内存管理问题strong
。
它似乎适用于系统颜色,因为这些系统颜色实例可能由 UIKit 保存在内存中。但是您的自定义颜色不是。
改变:
@property (assign) UIColor *pColor;
@property (assign) UIColor *sColor;
至:
@property (nonatomic, strong) UIColor *pColor;
@property (nonatomic, strong) UIColor *sColor;
如果有的话,您应该很少使用assign
对象指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句