发出绘图自定义UINavigationBar后退按钮

时间:2013-06-14 22:08:27

标签: ios uinavigationcontroller uinavigationbar quartz-graphics

我正在使用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];
}

0 个答案:

没有答案