CorePlot - multiLine attributed label - ios

I am trying to create a custom label for coreplot using NSAttributedString. Everything works fine when my strings have 1 line.
The problem occurs when I want to have 2 line strings using code:
NSMutableAttributedString* remFinalLabel = [remAttrStr mutableCopy];
NSMutableAttributedString *newLineAttrStr = [[NSMutableAttributedString alloc]initWithString:#"\n"];
[remFinalLabel appendAttributedString:newLineAttrStr];
[remFinalLabel appendAttributedString:rem2AttrStr];
The result looks like that: not even first string is properly displayed. How can I set the number of lines in custom label?
My code to create labels:
NSMutableArray* labelsStrings = [NSMutableArray arrayWithObjects:strAttr1, strAttr2, strAttr3, nil];
NSMutableArray *ticksLocations = [NSMutableArray arrayWithObjects:#0.5, #1.5, #2.5, nil];
NSMutableArray* customLabels = [[NSMutableArray alloc] init];
NSUInteger labelLocation = 0;
#try {
for (NSNumber *tickLocation in ticksLocations) {
NSAttributedString* currentLabel = [labelsStrings objectAtIndex:labelLocation];
CPTTextLayer *txtLayer = [[CPTTextLayer alloc] initWithAttributedText:currentLabel];
CPTAxisLabel* newLabel = [[CPTAxisLabel alloc] initWithContentLayer:txtLayer];
newLabel.tickLocation = tickLocation;
newLabel.offset = 0.0f;
newLabel.alignment = CPTAlignmentLeft;
[customLabels addObject:newLabel];
labelLocation++;
}
}
#catch (NSException * e) {
DLog(#"An exception occurred while creating date labels for x-axis");
}
#finally {
y.axisLabels = [NSSet setWithArray:customLabels];
}
y.majorTickLocations = [NSSet setWithArray:ticksLocations];

You can achieve this by setting the frame of content layer of your CPTAxisLabel.
Try this:-
CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:#"Your Text Here" textStyle:#"Text Style"];
[label.contentLayer setFrame:CGRectMake(0, 0, 40, 40)]; //change this frame according to your requirement
Happy Coding..!!

Related

Implementing chartValueSelected method in Charts library for iOS

I have a application, that can display charts with data using iOS Charts library v.2.3. Now I must enable the option to track touching points of data on the chart. I do some research and I know, that I must use the chartValueSelected method in class, that implements . I also declare chartView.delegate to self and connect outlet in view on the storyboard. But when I tested it, I always get a signal from the chartValueNothingSelected method, with none from chartValueSelected. It is something, that I should put in my code, that enables tracking touch on points in my application?
Edit: code
#interface ChartViewController () <ChartViewDelegate>
#end
#implementation ChartViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.chartView.delegate = self;
_chartView.dragEnabled = YES;
[_chartView setScaleEnabled:YES];
_chartView.pinchZoomEnabled = YES;
_chartView.drawGridBackgroundEnabled = NO;
// some random data generator
// x-axis limit line
ChartLimitLine *llXAxis = [[ChartLimitLine alloc] initWithLimit:10.0 label:#"Index 10"];
llXAxis.lineWidth = 4.0;
llXAxis.lineDashLengths = #[#(10.f), #(10.f), #(0.f)];
llXAxis.labelPosition = ChartLimitLabelPositionRightBottom;
llXAxis.valueFont = [UIFont systemFontOfSize:10.f];
//[_chartView.xAxis addLimitLine:llXAxis];
_chartView.xAxis.gridLineDashLengths = #[#10.0, #10.0];
_chartView.xAxis.gridLineDashPhase = 0.f;
ChartLimitLine *ll1 = [[ChartLimitLine alloc] initWithLimit:150.0 label:#"Upper Limit"];
ll1.lineWidth = 4.0;
ll1.lineDashLengths = #[#5.f, #5.f];
ll1.labelPosition = ChartLimitLabelPositionRightTop;
ll1.valueFont = [UIFont systemFontOfSize:10.0];
ChartLimitLine *ll2 = [[ChartLimitLine alloc] initWithLimit:-30.0 label:#"Lower Limit"];
ll2.lineWidth = 4.0;
ll2.lineDashLengths = #[#5.f, #5.f];
ll2.labelPosition = ChartLimitLabelPositionRightBottom;
ll2.valueFont = [UIFont systemFontOfSize:10.0];
ChartYAxis *leftAxis = _chartView.leftAxis;
[leftAxis removeAllLimitLines];
[leftAxis addLimitLine:ll1];
[leftAxis addLimitLine:ll2];
leftAxis.gridLineDashLengths = #[#5.f, #5.f];
leftAxis.drawZeroLineEnabled = NO;
leftAxis.drawLimitLinesBehindDataEnabled = YES;
_chartView.rightAxis.enabled = NO;
//[_chartView.viewPortHandler setMaximumScaleY: 2.f];
//[_chartView.viewPortHandler setMaximumScaleX: 2.f];
//_chartView.marker = marker;
_chartView.legend.form = ChartLegendFormLine;
[_chartView animateWithXAxisDuration:2.5];
NSMutableArray *xVals = [[NSMutableArray alloc] init];
for (int i = 0; i < 100; i++)
{
[xVals addObject:[#(i) stringValue]];
}
NSMutableArray *yVals = [[NSMutableArray alloc] init];
for (int i = 0; i < 100; i++)
{
double mult = (1000 + 1);
double val = (double) (arc4random_uniform(mult)) + 3;
[yVals addObject:[[ChartDataEntry alloc] initWithValue:val xIndex:i]];
}
LineChartDataSet *set1 = nil;
if (_chartView.data.dataSetCount > 0)
{
set1 = (LineChartDataSet *)_chartView.data.dataSets[0];
set1.yVals = yVals;
_chartView.data.xValsObjc = xVals;
[_chartView.data notifyDataChanged];
[_chartView notifyDataSetChanged];
}
else
{
set1 = [[LineChartDataSet alloc] initWithYVals:yVals label:#"DataSet 1"];
set1.lineDashLengths = #[#5.f, #2.5f];
set1.highlightLineDashLengths = #[#5.f, #2.5f];
[set1 setColor:UIColor.blackColor];
[set1 setCircleColor:UIColor.blackColor];
set1.lineWidth = 1.0;
set1.circleRadius = 3.0;
set1.drawCircleHoleEnabled = NO;
set1.valueFont = [UIFont systemFontOfSize:9.f];
//set1.fillAlpha = 65/255.0;
//set1.fillColor = UIColor.blackColor;
NSArray *gradientColors = #[
(id)[ChartColorTemplates colorFromString:#"#00ff0000"].CGColor,
(id)[ChartColorTemplates colorFromString:#"#ffff0000"].CGColor
];
CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
set1.fillAlpha = 1.f;
set1.fill = [ChartFill fillWithLinearGradient:gradient angle:90.f];
set1.drawFilledEnabled = YES;
CGGradientRelease(gradient);
NSMutableArray *dataSets = [[NSMutableArray alloc] init];
[dataSets addObject:set1];
LineChartData *data = [[LineChartData alloc] initWithXVals:xVals dataSets:dataSets];
_chartView.data = data;
}
}
- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight
{
NSLog(#"chartValueSelected");
}
- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
{
NSLog(#"chartValueNothingSelected");
}
#end
and from .h file
#import <UIKit/UIKit.h>
#import Charts;
#interface ChartViewController : UIViewController
#property(nonatomic, strong) IBOutlet LineChartView* chartView;
#property (strong, nonatomic) IBOutlet NSLayoutConstraint *chartViewHeightConstraint;
#end
For everyone, who will occurr similar problem to mine. I resolve my problem, cleaning everything, that can be left of old version 2.3 of Charts using CocoaPods tools and later add reference to new 3.0 version. For me, it enabled option to show actually clicked point.

How to set horizontal bar length in ios-charts?

I've used the ios-charts project on github and used the HorizontalCharts example. It works good in the example but when I try to set the horizontal bar value, the bar just gets too long. Example visible here:
My code is this:
-(void)setupChart{
myQuota = [[DataManager shared] myQuota];
[self setupBarLineChartView:_chartView];
_chartView.delegate = self;
_chartView.drawBarShadowEnabled = NO;
_chartView.drawValueAboveBarEnabled = YES;
_chartView.maxVisibleValueCount = 60;
ChartXAxis *xAxis = _chartView.xAxis;
xAxis.labelPosition = XAxisLabelPositionBottom;
xAxis.labelFont = [UIFont systemFontOfSize:10.f];
xAxis.drawAxisLineEnabled = YES;
xAxis.drawGridLinesEnabled = YES;
xAxis.gridLineWidth = .3;
ChartYAxis *leftAxis = _chartView.leftAxis;
leftAxis.labelFont = [UIFont systemFontOfSize:10.f];
leftAxis.drawAxisLineEnabled = YES;
leftAxis.drawGridLinesEnabled = YES;
leftAxis.drawLabelsEnabled = NO;
leftAxis.gridLineWidth = .3;
leftAxis.axisMinValue = 0.0;
ChartYAxis *rightAxis = _chartView.rightAxis;
rightAxis.enabled = YES;
rightAxis.labelFont = [UIFont systemFontOfSize:10.f];
rightAxis.drawAxisLineEnabled = YES;
rightAxis.drawGridLinesEnabled = NO;
rightAxis.axisMinValue = 0.0;
rightAxis.yOffset = 1.0;
rightAxis.axisMaxValue = [myQuota.quota doubleValue]; // here is 10
_chartView.doubleTapToZoomEnabled = NO;
_chartView.highlightPerTapEnabled = NO;
_chartView.legend.enabled = NO;
[_chartView animateWithYAxisDuration:2.5];
[self updateChartData];
}
- (void)updateChartData
{
if (self.shouldHideData)
{
_chartView.data = nil;
return;
}
if(myQuota != nil && myQuota.quota != nil)
{
[self setDataCount:(1) range: [myQuota.quota doubleValue]];
}
}
- (void)setDataCount:(int)count range:(double)range
{
NSMutableArray *xVals = [[NSMutableArray alloc] init];
[xVals addObject:myQuota.rowName];
NSMutableArray *yVals = [[NSMutableArray alloc] init];
double val = [myQuota.quotaReached doubleValue]; // here is 2
[yVals addObject:[[BarChartDataEntry alloc] initWithValue:val xIndex:0]];
BarChartDataSet *set1 = nil;
if (_chartView.data.dataSetCount > 0)
{
set1 = (BarChartDataSet *)_chartView.data.dataSets[0];
set1.yVals = yVals;
_chartView.data.xValsObjc = xVals;
[_chartView notifyDataSetChanged];
}
else
{
set1 = [[BarChartDataSet alloc] initWithYVals:yVals label:#""];
set1.barSpace = 0.35;
set1.colors = [NSArray arrayWithObjects:[UIColor greenColor], nil];
NSMutableArray *dataSets = [[NSMutableArray alloc] init];
[dataSets addObject:set1];
BarChartData *data = [[BarChartData alloc] initWithXVals:xVals dataSets:dataSets];
[data setValueFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:10.f]];
_chartView.data = data;
}
}
Why is the bar so long?
Okay, since nobody offered an answer I tried a HACK. I've added an invisible bar/row for which I set the value to the maximum of the bar chart. This way the axis shows the maximum even though the bar is invisible.
I welcome anybody who knows a better way but until then I'll do it like this:
- (void)setDataCount:(int)count range:(double)range{
MY_MAX_VALUE = 10; // put HERE your MAX value for the axis
NSMutableArray *xVals = [[NSMutableArray alloc] init];
[xVals addObject:myQuota.rowName];
NSMutableArray *yVals = [[NSMutableArray alloc] init];
double val = [myQuota.quotaReached doubleValue]; // here is 2
[yVals addObject:[[BarChartDataEntry alloc] initWithValue:val xIndex:0]];
[yVals addObject:[[BarChartDataEntry alloc] initWithValue: MY_MAX_VALUE xIndex:1]];
}

ios-charts radar chart turn auto scaling OFF

These two radar charts have the same data points for the orange bit, but different for the gray. However, as you can see it is autoscaling, and the orange bit ends up bigger on the second chart, even though they are the same exact data points. Is there a way to turn autoscaling off? I would like 100% to go right to the edge of the chart also.
-(void)setupRadarChart
{
self.radarChart.descriptionText = #"";
self.radarChart.webLineWidth = .75;
self.radarChart.innerWebLineWidth = 0.375;
self.radarChart.webAlpha = 1.0;
self.radarChart.userInteractionEnabled = NO;
self.radarChart.xAxis.enabled = YES;
ChartYAxis *yAxis = self.radarChart.yAxis;
yAxis.enabled = NO;
ChartLegend *l = self.radarChart.legend;
l.position = ChartLegendPositionBelowChartLeft;
l.font = [UIFont systemFontOfSize:UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 12 : (headerWidth/40)];
[self setRadarData];
}
- (void)setRadarData
{
NSMutableArray *parties = [[NSMutableArray alloc] init];
for (PillarModel *m in [DataManager sharedData].pillars)
{
[parties addObject:m.abbreviation];
}
NSMutableArray *yVals2 = [[NSMutableArray alloc] init];
NSMutableArray *benchMark = [[NSMutableArray alloc] init];
BOOL shouldAdd = YES;
for (PillarModel *pillar in [DataManager sharedData].pillars)
{ int totalPillarScore = (int)[[DataManager sharedData] getTotalScorePossible:[[DataManager sharedData] getIndividualQuestionResultsForPillar:pillar.pillarId]];
if ((isCompany ? [[DataManager sharedData] getCompanyScoresForCategory:pillar] : [[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId]) != 0)
{
shouldAdd = NO;
}
if (pillar.pillarId == numberOfPillars -1 && shouldAdd) {
[yVals2 addObject:[[ChartDataEntry alloc] initWithValue:0.01 xIndex:pillar.pillarId]];
}
else{
double val = (isCompany ? (double)[[DataManager sharedData] getCompanyScoresForCategory:pillar]/totalPillarScore : (double)[[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId] / totalPillarScore);
[yVals2 addObject:[[ChartDataEntry alloc] initWithValue:val xIndex:pillar.pillarId]];
}
float pillarBenchMark = [[[[[DataManager sharedData].benchmarkJSONDict objectForKey:hightlightedView.lowercaseString] objectForKey:pillar.title] objectForKey:#"pillar"] intValue];
float ifNoBenchMarkThanCompanyScore = (pillarBenchMark ? pillarBenchMark : (isCompany ? [[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId]: [[DataManager sharedData] getCompanyScoresForCategory:pillar]));
[benchMark addObject:[[ChartDataEntry alloc] initWithValue:ifNoBenchMarkThanCompanyScore/totalPillarScore xIndex:pillar.pillarId]];
}
NSMutableArray *xVals = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPillars; i++)
{
[xVals addObject:parties[i % parties.count]];
}
NSString *label = (isCompany ? #"Company score" : #"Your score");
RadarChartDataSet *set2 = [[RadarChartDataSet alloc] initWithYVals:yVals2 label:label];
[set2 setColor:[DataManager sharedData].mainColor];
set2.drawFilledEnabled = YES;
set2.fillAlpha = 1.0f;
set2.lineWidth = 2.0;
RadarChartDataSet *benchMarkSet = [[RadarChartDataSet alloc] initWithYVals:benchMark label:#"Benchmark"];
[benchMarkSet setColor:[UIColor colorWithRed:125/255.0f green:125/255.0f blue:125/255.0f alpha:0.6f]];
benchMarkSet.drawFilledEnabled = YES;
benchMarkSet.fillAlpha = 0.0f;
benchMarkSet.lineWidth = 2.0;
benchMarkSet.highlightLineDashLengths = #[[NSNumber numberWithInt:2]];
benchMarkSet.highlightLineDashPhase = 2;
RadarChartData *data = [[RadarChartData alloc] initWithXVals:xVals dataSets:#[set2, benchMarkSet]];
[data setValueFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:8.f]];
[data setDrawValues:NO];
self.radarChart.data = data;
}
The answer that was posted by 孙博弘 wasn't correct, but it led me to realise how easy this was to solve. This solves both the autoscaling problem and also now reaches the edge.
self.radarChart.yAxis.customAxisMin = 0;
self.radarChart.yAxis.customAxisMax = 1;
i'm afraid that you shouln't use customAxisMax directly as it use a Internal Access Levels.https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
/// Flag indicating that the axis-max value has been customized
internal var _customAxisMax: Bool = false
Instead, you can use axisMaxValue to control it.
/// The maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMin()` to undo this.
public var axisMaxValue: Double
{
get
{
return _axisMaximum
}
set
{
_customAxisMax = true
_axisMaximum = newValue
}
}
//2016-06-12 update
public var factor: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange)
}
RadarChartView will calculator a factor to transform values into pixels.
Maybe,you can use axisMinValue and axisMaxValue to control autoscale.

iOS 8.1 Only Displaying UITextView Intermittently

I have a template quiz application that has been on the app store in various guises for a while now, in general it receives good reviews and had no bug reports.
Recently I've had two bug reports, people using iPads with iOS 8.1.2 or 8.1.3, saying that now and again the UITextView that I use to show the questions is blank.
I've not been able to replicate this bug, but I would be grateful if someone could shed some light on it.
The objects questions and userAnswer are not nil so it is definitely a UITextView issue.
The Controller is here:
#interface ReviewController ()
#property (strong, nonatomic) IBOutlet UITextView *output;
#end
#implementation ReviewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setReviewText];
// Do any additional setup after loading the view.
}
-(void)setReviewText{
NSArray* questions = [[NSArray alloc] init];
questions = [_manager getAllQuestions];
NSMutableArray* userAnswer = [[NSMutableArray alloc] init];
userAnswer = [self answersAttributed];
if(questions == nil)
_output.text = #"Questions Error";
if (userAnswer == nil)
{
_output.text = #"Error";
}
NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];
int i = 0;
NSAttributedString *linebreak =[[NSAttributedString alloc] initWithString:#"\n"];
for (Question* q in questions)
{
if (i == [userAnswer count])
break;
NSAttributedString *qtext =[[NSAttributedString alloc] initWithString:q.questionText];
NSAttributedString *ctext =[[NSAttributedString alloc] initWithString:#"Correct Answer:\n"];
NSAttributedString *atext =[[NSAttributedString alloc] initWithString:q.answerText];
NSAttributedString *ytext =[[NSAttributedString alloc] initWithString:#"Your Answer:\n"];
NSAttributedString *utext =[[NSAttributedString alloc] initWithAttributedString:userAnswer[i]];
[mutableAttString appendAttributedString:qtext];
[mutableAttString appendAttributedString:linebreak];
[mutableAttString appendAttributedString:ctext];
[mutableAttString appendAttributedString:atext];
[mutableAttString appendAttributedString:linebreak];
[mutableAttString appendAttributedString:ytext];
[mutableAttString appendAttributedString:utext];
[mutableAttString appendAttributedString:linebreak];
[mutableAttString appendAttributedString:linebreak];
i++;
}
NSAttributedString* outText = [[NSAttributedString alloc] init];
outText = [mutableAttString mutableCopy];
_output.attributedText = outText;
[_output setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
}
-(NSMutableArray*)answersAttributed
{
NSMutableArray* ansAtt = [[NSMutableArray alloc] init];
NSArray* questions = [[NSArray alloc] init];
questions = [_manager getAllQuestions];
NSArray* userAnswers = [[NSArray alloc] init];
userAnswers = [_manager getAllUserAnswers];
if ([questions count] != [userAnswers count])
{
return ansAtt;
}
int i = 0;
for (NSString* userAnswer in userAnswers )
{
if([[questions[i] answerText] isEqualToString:userAnswer] )
{
NSDictionary *attributes = #{NSBackgroundColorAttributeName:[UIColor greenColor]};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:userAnswer attributes:attributes];
[ansAtt addObject:attrString];
}
else
{
NSDictionary *attributes = #{NSBackgroundColorAttributeName:[UIColor redColor]};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:userAnswer attributes:attributes];
[ansAtt addObject:attrString];
}
i++;
}
return ansAtt;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"review2results"])
{
// Get reference to the destination view controller
ReviewController *vc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
[vc setManager:_manager];
}
}
With autolayout, if you don't have enough constraints to fully specify size and position, then sometimes you'll see and and sometimes you won't. The unspecified constraints can have random values, like 0 height or off screen position.
Check to make sure the constraints are fully specified.
In my case textview marked as Non-Editable and Non-Selectable in Storyboard have the same strange behavior on iOS 8.1 (no problems in iOS 9+).
- (void)viewDidLoad {
[super viewDidLoad];
textview.attributedText = [[NSAttributedString alloc] initWithString:#"non-nil"]];
value = textview.attributedText;
//^ value is nil !!!
}
Fixed with this:
- (void)viewDidLoad {
[super viewDidLoad];
textview.editable = YES;
textview.attributedText = [[NSAttributedString alloc] initWithString:#"non-nil"]];
textview.editable = NO;
value = textview.attributedText;
//^ value is #"non-nil" now !!!
}

How to create two text columns in PDF?

The problem is to create two text columns in PDF like this:
For generating PDF I use Apple's guide "Drawing and Printing Guide for iOS", two columns I create with tabs:
NSArray *stringList =
#[
#[string1, string2],
#[#"", string4],
#[string5, string6],
#[string7, string8]
];
resultString = [[NSMutableAttributedString alloc] init];
for (NSArray *row in stringList) {
int i = 0;
NSMutableAttributedString *subResult = [[NSMutableAttributedString alloc] init];
NSMutableArray *tabs = #[].mutableCopy;
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
for (NSString *tempString in row) {
NSTextTab *tab = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:200 options:nil];
if ([tempString isKindOfClass:[NSAttributedString class]]) {
[subResult appendAttributedString:(NSAttributedString *)tempString];
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:#"\t"]];
} else {
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#\t", tempString]]];
}
[tabs addObject:tab];
i++;
}
[subResult appendAttributedString:[[NSAttributedString alloc] initWithString:#"\n"]];
[style setTabStops:tabs];
[subResult addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, subResult.length)];
[resultString appendAttributedString:subResult];
}
As output I get this:
So, the lines of my string marked with red arrows I want see entirely in the second column, like in the picture №1.
The idea is to split the text into blocks and single lines and to use for each part
- (void)drawInRect:(CGRect)rect;
or
void CTLineDraw(CTLineRef line, CGContextRef context);
Solution:
#import CoreText;
<...>
- (IBAction)createPDF:(id)sender {
PDFFileName = <yourString>;
PDFPath = <yourPath>;
[self generatePdfWithFilePath:PDFPath];
}
- (void)generatePdfWithFilePath:(NSString *)thefilePath {
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);
BOOL done = NO;
do {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 712), nil);
[self drawText];
done = YES;
}
while (!done);
UIGraphicsEndPDFContext();
}
- (void)drawText {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//Here you can set up attributes for your text
NSDictionary *attributesForText = #{
NSFontAttributeName:[UIFont fontWithName:#"Georgia" size:12]
};
//Drawing text in line
NSMutableAttributedString *stringOneAttributed = [[NSMutableAttributedString alloc] initWithString:stringOne attributes:attributesForText];
CTLineRef stringOneLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)(stringOneAttributed));
CGContextSetTextPosition(currentContext, x, y);
CTLineDraw(stringOneLine, currentContext);
CFRelease(stringOneLine);
//Drawing block of text in rectangle
NSMutableAttributedString *stringTwoAttributed = [[NSMutableAttributedString alloc] initWithString:stringTwo attributes:attributesForText];
[stringTwoAttributed drawInRect:CGRectMake(x, y, width, height)];
}

Resources