0

我正在使用 Quartz 2D 绘制一个后退箭头(如小于号 - <)作为 UINavigationController 的后退按钮。这对于普通按钮工作正常,但在选择按钮(UIControlStateSelected)时不会更改图像。有任何想法吗?

- (void)changeBackButton {
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    CGRect buttonFrame = CGRectMake(0,0,54,32);
    backBtn.frame = buttonFrame;

    UIGraphicsBeginImageContextWithOptions(buttonFrame.size, false, 0);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    UIColor *buttonColor = [UIColor darkTextColor];
    CGContextSetStrokeColorWithColor(ctx, buttonColor.CGColor);
    CGContextSetLineWidth(ctx, 2);

    CGContextBeginPath(ctx);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextMoveToPoint   (ctx, CGRectGetMinX(buttonFrame) + 14.0, CGRectGetMidY(buttonFrame)); 
    CGContextAddLineToPoint(ctx, CGRectGetMidX(buttonFrame), CGRectGetMinY(buttonFrame) + 4.0);
    CGContextStrokePath(ctx);
    CGContextMoveToPoint   (ctx, CGRectGetMinX(buttonFrame) + 14.0, CGRectGetMidY(buttonFrame));
    CGContextAddLineToPoint(ctx, CGRectGetMidX(buttonFrame), CGRectGetMaxY(buttonFrame) - 4.0);
    CGContextStrokePath(ctx);
    UIImage *backNormalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [backBtn setImage:backNormalImage forState:UIControlStateNormal];

    UIGraphicsBeginImageContextWithOptions(buttonFrame.size, false, 0);
    ctx = UIGraphicsGetCurrentContext();
    buttonColor = [UIColor lightTextColor];
    CGContextSetStrokeColorWithColor(ctx, buttonColor.CGColor);
    CGContextSetLineWidth(ctx, 2);

    CGContextBeginPath(ctx);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextMoveToPoint   (ctx, CGRectGetMinX(buttonFrame) + 14.0, CGRectGetMidY(buttonFrame));
    CGContextAddLineToPoint(ctx, CGRectGetMidX(buttonFrame), CGRectGetMinY(buttonFrame) + 4.0);
    CGContextStrokePath(ctx);
    CGContextMoveToPoint   (ctx, CGRectGetMinX(buttonFrame) + 14.0, CGRectGetMidY(buttonFrame));
    CGContextAddLineToPoint(ctx, CGRectGetMidX(buttonFrame), CGRectGetMaxY(buttonFrame) - 4.0);
    CGContextStrokePath(ctx);
    UIImage *backSelectedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

#warning This is not working
    [backBtn setImage:backSelectedImage forState:UIControlStateSelected];

    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.backBarButtonItem = nil;
    self.navigationItem.leftBarButtonItem = barButtonItem;
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}
4

0 回答 0