我有一个 mapView,它有 34 个 CAShapeLayer 来渲染每个省,另外 34 个 CATextLayer 来渲染每个省的名称。我将计算每个省的中心。
现在我将此 mapView 添加到 UIScrollView 中,当我缩放 mapView 时,我想重新绘制 CATextLayer 以使用另一个字体大小。所以在缩放之后,我会手动移除所有的 CATextLayer 并重新绘制它们,如下所示。
但是,我发现,for循环结束后,子层中还有一些CATextLayer,准确的说,每次测试,有18个CATextLayer没有被删除。我从来没有遇到过这个问题,我错过了什么吗?请帮忙,谢谢。
-(void)drawLabelsWithFontSize:(CGFloat)fontSize {
int i = 0;
NSUInteger count = [self.mapView.layer.sublayers count];
for (i = 0; i < count; i++) {
CALayer *layer = self.mapView.layer.sublayers[i];
if ([layer isKindOfClass:[CATextLayer class]]) {
[layer removeFromSuperlayer];
// NSLog(@"%@, %lu",[layer class],i);
} else {
// NSLog(@"%@",[layer class]);
}
}
// at here, some CATextLayer still in self.mapView.layer.sublayers
__block typeof(self) weakSelf = self;
NSDictionary *labelNameAndLocation = [self getLabelNameAndLocationInfo];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.alignment = NSTextAlignmentCenter;
[labelNameAndLocation enumerateKeysAndObjectsWithOptions:NSEnumerationReverse usingBlock:^(id key, id obj, BOOL *stop) {
if ([(NSString *)key length] > 0) {
NSDictionary *location = (NSDictionary *)obj;
CATextLayer *label = [CATextLayer layer];
CGPoint caculateCenter = CGPointMake([weakSelf longitudeToCoordinate:[location[@"lng"] doubleValue]],[weakSelf latitudeToCoordinate:[location[@"lat"] doubleValue]]);
NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
initWithString:key
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],
NSParagraphStyleAttributeName:paragraphStyle,
NSForegroundColorAttributeName:[UIColor blackColor]}];
CGSize size = [text size];
[label setBounds:CGRectMake(0, 0, size.width, size.height)];
[label setString:text];
label.position = caculateCenter;
label.contentsScale = [[UIScreen mainScreen] scale];
[weakSelf.mapView.layer addSublayer:label];
}
}];
}