Display fraction number in UILabel

前端 未结 5 586
情歌与酒
情歌与酒 2020-12-17 08:20

I am working on the app in which I have to show fraction number on label.

NSMutableAttributedString   * hogan = [[NSMutableAttributedString alloc] initWithSt         


        
5条回答
  •  庸人自扰
    2020-12-17 08:54

    I don't know if there is any other solution to have frictions inside "normal" UILabel, but You can create your own.

    Create new class extend from UIView and draw two string and line in between.

    You can use

    [str drawAtPoint:CGPointMake(x,y)]
    

    Than you just write a set method that takes two numbers or setter for decimal number and than you convert this into friction.

    - (void) setFractionValue: (NSNumber * ) a divider: (NSNumber * ) b {
    
        // Draw fraction a/b
        [[NSString stringWithFormat:@"%@", a] drawAtPoint:CGPointMake(x,y1)] ;
        [[NSString stringWithFormat:@"%@", b] drawAtPoint:CGPointMake(x,y2)] ;
    }
    

    or use something like this :

    - (void) setDecimalValue: (NSNumber *) decimal {
    
        // convert decimal to fraction 
        // get a and b from fraction
        // Draw fraction a/b
        [[NSString stringWithFormat:@"%@", a] drawAtPoint:CGPointMake(x,y1)] ;
        [[NSString stringWithFormat:@"%@", b] drawAtPoint:CGPointMake(x,y2)] ;
    
    }
    

    EDIT


    Use case :

     @implementation TestDrawText
    
    
    - (void)drawRect:(CGRect)rect {
    
        [super drawRect:rect];
    
    
    
        [self drawText:rect.origin.x + 10 yPosition:rect.origin.x + 10 text:@"2"];
    
        [self drowLine:rect.origin.x + 11 yPosition:rect.origin.x + 30];
    
        [self drawText:rect.origin.x + 20 yPosition:rect.origin.x + 20 text:@"5"];
    }
    
    - (void)drawText:(CGFloat)xPosition yPosition:(CGFloat)yPosition text: (NSString * ) text{
    
        CGPoint point = CGPointMake(xPosition, yPosition);
        NSDictionary* textFontAttributes = @{NSFontAttributeName: [UIFont fontWithName: @"Helvetica" size: 12], NSForegroundColorAttributeName: UIColor.redColor};
        [text drawAtPoint:point withAttributes:textFontAttributes];
    }
    
    - (void) drowLine:(CGFloat)xPosition yPosition:(CGFloat)yPosition {
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
        // Draw them with a 2.0 stroke width so they are a bit more visible.
        CGContextSetLineWidth(context, 2.0f);
    
        CGContextMoveToPoint(context, xPosition, yPosition); //start at this point
    
        CGContextAddLineToPoint(context, xPosition + 15, yPosition - 15); //draw to this point
    
        // and now draw the Path!
        CGContextStrokePath(context);
    }
    

    This is quick example and need to be configure to your wishes, but is a start from where you could go.

提交回复
热议问题