FSInteractiveMap Objective-C to Swfit translate - objective-c

i want to use FSInteractiveMap in swift
but documentations are only is Objective-C and i can't Translate click Handler in swift.
NSDictionary* data = #{ #"asia" : #12,
#"australia" : #2,
#"north_america" : #5,
#"south_america" : #14,
#"africa" : #5,
#"europe" : #20
};
FSInteractiveMapView* map = [[FSInteractiveMapView alloc] initWithFrame:self.view.frame];
[map loadMap:#"world-continents-low" withData:data colorAxis:#[[UIColor lightGrayColor], [UIColor darkGrayColor]]];
in swift working with:
let map: FSInteractiveMapView = FSInteractiveMapView()
map.frame = self.view.frame
var mapData = [String: Int]()
mapData["IR-01"] = 0
mapData["IR-02"] = 10
var mapColors = [UIColor]()
mapColors.append(UIColor(red:0.26, green:0.112, blue:0.0, alpha:1.0))
mapColors.append(UIColor(red:0.45, green:0.132, blue:0.0, alpha:1.0))
map.loadMap("iranHigh", withData:mapData, colorAxis:mapColors)
view.addSubview(map)
view.setNeedsDisplay()
its working correctly but i cant add click Handler
here is documentation in Objective-C:
FSInteractiveMapView* map = [[FSInteractiveMapView alloc] initWithFrame:CGRectMake(16, 96, self.view.frame.size.width - 32, 500)];
[map loadMap:#"usa-low" withColors:nil];
[map setClickHandler:^(NSString* identifier, CAShapeLayer* layer) {
if(_oldClickedLayer) {
_oldClickedLayer.zPosition = 0;
_oldClickedLayer.shadowOpacity = 0;
}
_oldClickedLayer = layer;
// We set a simple effect on the layer clicked to highlight it
layer.zPosition = 10;
layer.shadowOpacity = 0.5;
layer.shadowColor = [UIColor blackColor].CGColor;
layer.shadowRadius = 5;
layer.shadowOffset = CGSizeMake(0, 0);
}];
OR:
[map setClickHandler:^(NSString* identifier, CAShapeLayer* layer) {
self.detailDescriptionLabel.text = [NSString stringWithFormat:#"Continent clicked: %#", identifier];}];
how can i do it in Swift?

add some code, looks like that
override func viewDidLoad() {
super.viewDidLoad()
let map: FSInteractiveMapView = FSInteractiveMapView()
weak var oldClickedLayer = CAShapeLayer()
var mapData = [String: Int]()
mapData["asia"] = 12
mapData["australia"] = 2
mapData["north_america"] = 5
mapData["south_america"] = 14
mapData["africa"] = 5
mapData["europe"] = 20
var mapColors = [UIColor]()
mapColors.append(UIColor.lightGray)
mapColors.append(UIColor.darkGray)
map.frame = self.view.frame
map.clickHandler = {(identifier: String? , _ layer: CAShapeLayer?) -> Void in
if (oldClickedLayer != nil) {
oldClickedLayer?.zPosition = 0
oldClickedLayer?.shadowOpacity = 0
}
oldClickedLayer = layer
// We set a simple effect on the layer clicked to highlight it
layer?.zPosition = 10
layer?.shadowOpacity = 0.5
layer?.shadowColor = UIColor.black.cgColor
layer?.shadowRadius = 5
layer?.shadowOffset = CGSize(width: 0, height: 0)
print("clicked")
}
let mapName: String! = String("world-continents-low")
map.loadMap(mapName, withData:mapData, colorAxis:mapColors)
view.addSubview(map)
view.setNeedsDisplay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
that worked for me.
Don't forget to import library

Related

CAEmitterLayer CAEmitterCell animation bug

CAEmitterCell contents picCAEmitterLayer emits multiple CAEmitterCells with specified trajectories. When the trajectory CAEmitterCells fly to the end of time, it will become a particle graph displayed by CAEmitterCells, and then the particle graph will be scattered 360 °. However, only one trajectory particle can be animated completely, but more than two particles will appear. The trajectory particle graph will turn white
Adding a boomEmitterCell will cause the contents of CAEmitterCell in getDogLeftDownEmitterWithImageName and getRedLeftEmitterWithImageName to not display the picture and white blocks
CAEmitterLayer *emitterLayer = [[CAEmitterLayer alloc] init];
emitterLayer.emitterPosition = CGPointMake(self.view.layer.bounds.size.width -100, self.view.layer.bounds.size.height - 100);
emitterLayer.emitterSize = CGSizeMake(50, 100.f);
emitterLayer.emitterShape = kCAEmitterLayerLine;
emitterLayer.emitterMode = kCAEmitterLayerOutline;
emitterLayer.renderMode = kCAEmitterLayerOldestLast;
CAEmitterCell *dogleftEmitterCell = [self getRedLeftEmitterWithImageName:[imageArray objectAtIndex:0]];
CAEmitterCell *redLeftEmitterCell = [self getRedLeftEmitterWithImageName:[imageArray objectAtIndex:0]];
emitterLayer.emitterCells = #[dogleftEmitterCell,redLeftEmitterCell];
[self.view.layer addSublayer:emitterLayer];
//狗头左下
- (CAEmitterCell *)getDogLeftDownEmitterWithImageName:(NSString *)imageName {
CAEmitterCell *emitterCell = [[CAEmitterCell alloc] init];
emitterCell.name = #"左下狗头";
emitterCell.contents = (__bridge id _Nullable)[UIImage imageNamed:#"emoji_6"].CGImage;
//产生频率
emitterCell.birthRate = 1;
//存活时长
emitterCell.lifetime = 0.6;
//速度
emitterCell.velocity = 100;
emitterCell.xAcceleration = -1000.f; // 模拟重力影响
emitterCell.scale = 0.2;
emitterCell.scaleSpeed = 0.25;
emitterCell.emissionLongitude = M_PI_2;
// emitterCell.emissionRange = M_PI_4;
emitterCell.emitterCells = #[[self boomEmitterCell]];
return emitterCell;
}
//红包左上
- (CAEmitterCell *)getRedLeftEmitterWithImageName:(NSString *)imageName {
CAEmitterCell *emitterCell = [[CAEmitterCell alloc] init];
emitterCell.name = #"红包";
emitterCell.contents = (__bridge id _Nullable)[UIImage imageNamed:#"emoji_7"].CGImage;
//产生频率
emitterCell.birthRate = 10;
//存活时长
emitterCell.lifetime = 0.6;
// emitterCell.beginTime = self.beginTime;
//速度
emitterCell.velocity = 100;
emitterCell.yAcceleration = -1000.f; // 模拟重力影响
emitterCell.scale = 0.2;
// emitterCell.scaleRange = 0.06;
emitterCell.scaleSpeed = 0.25;
emitterCell.emissionLongitude = M_PI;
// CAEmitterCell *emitterCell = [self boomEmitterCell];
emitterCell.emitterCells = #[[self boomEmitterCell]];
return emitterCell;
}
- (CAEmitterCell *)boomEmitterCell {
// 爆炸
CAEmitterCell * explodeCell = [CAEmitterCell emitterCell];
explodeCell.name = #"explodeCell";
explodeCell.birthRate = 2.f;
explodeCell.lifetime = 0.6f;
// explodeCell.velocity = 0.f;
// explodeCell.scale = 1.0;
// explodeCell.redSpeed = -1.5; //爆炸的时候变化颜色
// explodeCell.blueRange = 1.5; //爆炸的时候变化颜色
// explodeCell.greenRange = 1.f; //爆炸的时候变化颜色
// explodeCell.birthRate = 1.0;
// explodeCell.velocity = 0;
// explodeCell.scale = 2.5;
// explodeCell.redSpeed =-1.5;
// explodeCell.blueSpeed =+1.5;
// explodeCell.greenSpeed =+1.0;
// explodeCell.lifetime = 0.35;
explodeCell.contents = (__bridge id _Nullable)[[UIImage imageNamed:#"allStart"] CGImage];
// 火花
// CAEmitterCell * sparkCell = [CAEmitterCell emitterCell];
// sparkCell.name = #"sparkCell";
//
// sparkCell.birthRate = 3.f;
// sparkCell.lifetime = 3.f;
// sparkCell.velocity = 125.f;
//// sparkCell.yAcceleration = 75.f; // 模拟重力影响
// sparkCell.emissionRange = M_PI * 2; // 360度
//
// sparkCell.scale = 1.2f;
// sparkCell.contents = (id)[[UIImage imageNamed:#"star_white_stroke"] CGImage];
// sparkCell.redSpeed = 0.4;
// sparkCell.greenSpeed = -0.1;
// sparkCell.blueSpeed = -0.1;
// sparkCell.alphaSpeed = -0.25;
// explodeCell.emitterCells = #[sparkCell];
return explodeCell;
}

How to get Image size from URL in ios

How can I get the size(height/width) of an image from URL in objective-C? I want my container size according to the image. I am using AFNetworking 3.0.
I could use SDWebImage if it fulfills my requirement.
Knowing the size of an image before actually loading it can be necessary in a number of cases. For example, setting the height of a tableView cell in the heightForRowAtIndexPath method while loading the actual image later in the cellForRowAtIndexPath (this is a very frequent catch 22).
One simple way to do it, is to read the image header from the server URL using the Image I/O interface:
#import <ImageIO/ImageIO.h>
NSMutableString *imageURL = [NSMutableString stringWithFormat:#"http://www.myimageurl.com/image.png"];
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSLog(#"Image header %#",imageHeader);
NSLog(#"PixelHeight %#",[imageHeader objectForKey:#"PixelHeight"]);
Swift 4.x
Xcode 12.x
func sizeOfImageAt(url: URL) -> CGSize? {
// with CGImageSource we avoid loading the whole image into memory
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
return nil
}
let propertiesOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, propertiesOptions) as? [CFString: Any] else {
return nil
}
if let width = properties[kCGImagePropertyPixelWidth] as? CGFloat,
let height = properties[kCGImagePropertyPixelHeight] as? CGFloat {
return CGSize(width: width, height: height)
} else {
return nil
}
}
Use Asynchronous mechanism called GCD in iOS to dowload image without affecting your main thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Download IMAGE using URL
NSData *data = [[NSData alloc]initWithContentsOfURL:URL];
// COMPOSE IMAGE FROM NSData
UIImage *image = [[UIImage alloc]initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
// UI UPDATION ON MAIN THREAD
// Calcualte height & width of image
CGFloat height = image.size.height;
CGFloat width = image.size.width;
});
});
For Swift 4 use this:
let imageURL = URL(string: post.imageBigPath)!
let source = CGImageSourceCreateWithURL(imageURL as CFURL,
let imageHeader = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil)! as NSDictionary;
print("Image header: \(imageHeader)")
The header would looks like:
Image header: {
ColorModel = RGB;
Depth = 8;
PixelHeight = 640;
PixelWidth = 640;
"{Exif}" = {
PixelXDimension = 360;
PixelYDimension = 360;
};
"{JFIF}" = {
DensityUnit = 0;
JFIFVersion = (
1,
0,
1
);
XDensity = 72;
YDensity = 72;
};
"{TIFF}" = {
Orientation = 0;
}; }
So u can get from it the Width, Height.
you can try like this:
NSData *data = [[NSData alloc]initWithContentsOfURL:URL];
UIImage *image = [[UIImage alloc]initWithData:data];
CGFloat height = image.size.height;
CGFloat width = image.size.width;

IOS::How to get the MPMediaquery Songsquery Artwork

I'm using this code for getting the Artwork, but it's not workout for me. What's the wrong in this code.Suggest me.
Thanks.
MPMediaQuery *mySongsQuery = [MPMediaQuery songsQuery];
NSArray *SongsList = [mySongsQuery collections];
for (MPMediaItemCollection *SongsArt in SongsList) {
NSArray *songs = [SongsArt items];
for (MPMediaItem *song in songs) {
if ([(MPMediaItem*)item valueForProperty:MPMediaItemPropertyAssetURL] != nil) {
CGSize artworkImageViewSize = CGSizeMake(40, 40);
MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];
UIImage * image = [artwork imageWithSize:artworkImageViewSize];
if (image!= nil)
{
imgv_songImageView.image = image;
}
else
{
imgv_songImageView.image = [UIImage imageNamed:#"musicD-jpeg.png"];
}
}
}
I assume you just want to loop through all songs in the music library so I don't see a need for collections:
MPMediaQuery *mySongsQuery = [MPMediaQuery songsQuery];
for (MPMediaItem *item in mySongsQuery.items) {
if (![[item valueForProperty:MPMediaItemPropertyIsCloudItem]boolValue]) {
CGSize artworkImageViewSize = CGSizeMake(40, 40);
MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];
UIImage *image = [artwork imageWithSize:artworkImageViewSize];
if (image) {
imgv_songImageView.image = image;
} else {
imgv_songImageView.image = [UIImage imageNamed:#"musicD-jpeg.png"];
}
}
}
I'm not sure why you want to check for the Asset URL but I've left it in.
Here i am posting the code to get the tracks and sorting them alphabetically. Its written in swift3.
/// Get all the songs in the device and display in the tableview
///
func getAllSongs() {
let query: MPMediaQuery = MPMediaQuery.songs()
let allSongs = query.items
allSongItems?.removeAll()
guard allSongs != nil else {
return
}
var index = 0
for item in allSongs! {
let pathURL: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
if pathURL == nil {
print("#Warning!!! Track : \(item) is not playable.")
} else {
let trackInfo = SongItem()
trackInfo.index = index
trackInfo.mediaItem = item
let title = item.value(forProperty: MPMediaItemPropertyTitle) as? String ?? "<Unknown>"
let artistName = item.value(forProperty: MPMediaItemPropertyArtist) as? String ?? "<Unknown>"
trackInfo.songName = title
trackInfo.artistName = artistName
trackInfo.isSelected = false
trackInfo.songURL = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
allSongItems?.append(trackInfo)
index += 1
}
}
// Sort the songs alphabetically
let sortedArray: [SongItem]? = allSongItems?.sorted {
$0.songName!.localizedCompare($1.songName!) == .orderedAscending
}
allSongItems?.removeAll()
if let arr = sortedArray {
allSongItems?.append(contentsOf: arr)
}
}

Core-Plot unable to plot multiple graphs on one page (iPad)

I am trying to display multiple chart's on one screen but i am not able to get it to work. I am trying to get to a point where i have 3 x pieGraphs and 1 x scattered graph on this display.
I have tried: Unable to have two CorePlot graphs show simultaneously but not been able to solve this. I am using the example app from Core-Plot as a base for the design of the code. I see no difference when i try to emulate the solution to that problem in my code.
I am able to display the first pie chart: "matchPieChart" but not the second one "questionsPieChart". It does not look like it even process the second chart.
Without consideration of the other similar problem solution (above) the result is:
The legend on the right side is the one that is associated with the pie that is displayed to the left, i guess it hook up to the second pie that i try to display. It is displayed where the second pie chart should be displayed.
Here is the code execution, see the NSLog in the code:
iPad_matchPieChartConfiguration
numberOfRecordsForPlot:
numberOfRecordsForPlot:
numberForPlot:
numberForPlot:
numberOfRecordsForPlot:
numberOfRecordsForPlot:
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
iPad_questionsPieChartConfiguration
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
dataLabelForPlot:
dataLabelForPlot: matchPieChart
dataLabelForPlot:
dataLabelForPlot: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
legendTitleForPieChart: matchPieChart
And here is the actual code:
-(void)iPad_matchPieChartConfiguration {
NSLog(#"iPad_matchPieChartConfiguration");
// Set titles
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of Games played: %.0f", nrGamesPlayed];
title_Matches_label.text = myString;
//Create host view
matchChartView = [[CPTGraphHostingView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:matchChartView];
matchPieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
matchChartView.hostedGraph = matchPieGraph;
matchPieGraph.plotAreaFrame.masksToBorder = NO;
matchPieGraph.paddingLeft = 10.0;
matchPieGraph.paddingTop = 120.0;
matchPieGraph.paddingRight = 350.0;
matchPieGraph.paddingBottom = 360.0;
matchPieGraph.axisSet = nil;
//====ADD MATCH PIE CHART====//
matchPiePlot = [[CPTPieChart alloc]init];
matchPiePlot.dataSource = self;
matchPiePlot.pieRadius = 100.0;
matchPiePlot.identifier = #"matchPieChart";
matchPiePlot.startAngle = M_PI_4;
matchPiePlot.sliceDirection = CPTPieDirectionCounterClockwise;
matchPiePlot.borderLineStyle = [CPTLineStyle lineStyle];
matchPiePlot.labelOffset = 5.0;
matchPieGraph.titleTextStyle = whiteText;
[matchPieGraph addPlot:matchPiePlot];
// 1 - Get graph instance
CPTGraph *matchGraph = matchChartView.hostedGraph;
// 2 - Create legend
CPTLegend *theMatchLegend = [CPTLegend legendWithGraph:matchGraph];
// 3 - Configure legen
CPTMutableTextStyle *legendMatchTextStyle = [CPTTextStyle textStyle];
legendMatchTextStyle.fontSize = 12.0f;
legendMatchTextStyle.fontName = #"Noteworthy-Bold";
legendMatchTextStyle.color = [CPTColor whiteColor];
theMatchLegend.numberOfColumns = 2;
theMatchLegend.fill = nil;
theMatchLegend.borderLineStyle = nil;
theMatchLegend.cornerRadius = 5.0;
theMatchLegend.textStyle = legendMatchTextStyle;
// 4 - Add legend to graph
matchGraph.legend = theMatchLegend;
matchGraph.legendAnchor = CPTRectAnchorRight;
matchGraph.legendDisplacement = CGPointMake(-460.0, -10.0);
}
-(void)iPad_questionsPieChartConfiguration {
NSLog(#"iPad_questionsPieChartConfiguration");
// Set titles
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of Questions answered: %.0f", nrQuestionsAnswered];
title_Questions_label.text = myString;
//Create host view
questionsChartView = [[CPTGraphHostingView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
[self.view addSubview:questionsChartView];
questionsPieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
questionsChartView.hostedGraph = matchPieGraph;
questionsPieGraph.plotAreaFrame.masksToBorder = NO;
questionsPieGraph.paddingLeft = 10.0;
questionsPieGraph.paddingTop = 120.0;
questionsPieGraph.paddingRight = 150.0;
questionsPieGraph.paddingBottom = 360.0;
questionsPieGraph.axisSet = nil;
//====ADD MATCH PIE CHART====//
questionsPiePlot = [[CPTPieChart alloc]init];
questionsPiePlot.dataSource = self;
questionsPiePlot.pieRadius = 100.0;
questionsPiePlot.identifier = #"questionsPieChart";
questionsPiePlot.startAngle = M_PI_4;
questionsPiePlot.sliceDirection = CPTPieDirectionCounterClockwise;
questionsPiePlot.borderLineStyle = [CPTLineStyle lineStyle];
questionsPiePlot.labelOffset = 5.0;
questionsPieGraph.titleTextStyle = whiteText;
[questionsPieGraph addPlot:questionsPiePlot];
// 1 - Get graph instance
CPTGraph *questionsGraph = questionsChartView.hostedGraph;
// 2 - Create legend
CPTLegend *theQuestionsLegend = [CPTLegend legendWithGraph:questionsGraph];
// 3 - Configure legen
CPTMutableTextStyle *legendQuestionsTextStyle = [CPTTextStyle textStyle];
legendQuestionsTextStyle.fontSize = 12.0f;
legendQuestionsTextStyle.fontName = #"Noteworthy-Bold";
legendQuestionsTextStyle.color = [CPTColor whiteColor];
theQuestionsLegend.numberOfColumns = 2;
theQuestionsLegend.fill = nil;
theQuestionsLegend.borderLineStyle = nil;
theQuestionsLegend.cornerRadius = 5.0;
theQuestionsLegend.textStyle = legendQuestionsTextStyle;
// 4 - Add legend to graph
questionsGraph.legend = theQuestionsLegend;
questionsGraph.legendAnchor = CPTRectAnchorRight;
questionsGraph.legendDisplacement = CGPointMake(-160.0, -10.0);
}
- (void)viewDidLoad {
[super viewDidLoad];
playerName_label.text = playerName;
AccessPlayerData *checkPlayerDiffFunction = [AccessPlayerData new];
int diffLevel = [checkPlayerDiffFunction checkPlayersDifficultyLevel:playerName];
switch (diffLevel) {
case 1:
playerDifficulty_label.text = #"Difficuly Level: Children / Easy";
break;
case 2:
playerDifficulty_label.text = #"Difficuly Level : Teenager / Medium";
break;
case 3:
playerDifficulty_label.text = #"Difficuly Level: Adult / Hard";
break;
default:
break;
}
nrGamesPlayed_label.text = [NSString stringWithFormat:#"Total number of games played: %.0f", nrGamesPlayed];
//====IF THIS IS IPAD PROCESS ALL GRAPHS====//
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
double nrOfSingleGames = nrGamesPlayed -(nrGamesWon + nrGamesLost);
double nrOfTotalGames = nrGamesPlayed;
double percentageNrOfSingleGames = (nrOfSingleGames / nrOfTotalGames) * 100;
double percentageNrOfMatchGames = ((nrOfTotalGames - nrOfSingleGames) / nrOfTotalGames) * 100;
NSString *singleGames = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrOfSingleGames, percentageNrOfSingleGames];
NSString *matchesGames = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", (nrOfTotalGames - nrOfSingleGames), percentageNrOfMatchGames];
//=========ADD DATA FOR MATCHES PIE GRAPH==========//
NSMutableArray *contentMatchArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:nrOfSingleGames], [NSNumber numberWithDouble:(nrOfTotalGames - nrOfSingleGames)], nil];
labelMatchOrder = [[NSArray alloc]initWithObjects:singleGames, matchesGames, nil];
legendMatchOrder = [[NSArray alloc] initWithObjects:#"Single Games", #"Matches", nil];
self.dataForMatchChart = contentMatchArray;
//=========ADD DATA FOR QUESTIONS PIE GRAPH==========//
nrQuestionsWrongAnswers = nrQuestionsAnswered - nrQuestionsCorrectAnswered;
double percentageCorrectAnswers = (nrQuestionsCorrectAnswered / nrQuestionsAnswered) * 100;
double percentageWrongAnswers = (nrQuestionsWrongAnswers / nrQuestionsAnswered) * 100;
NSString *answerCorrect = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrQuestionsCorrectAnswered, percentageCorrectAnswers];
NSString *answerWrong = [[NSString alloc]initWithFormat:#"%.0f (%.0f%%)", nrQuestionsWrongAnswers, percentageWrongAnswers];
playerName_label.text = playerName;
myString = [[NSString alloc]initWithFormat:#"Total number of questions answered: %.0f",nrQuestionsAnswered];
title_Questions_label.text = myString;
NSMutableArray *contentQuestionsArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:nrQuestionsWrongAnswers], [NSNumber numberWithDouble:nrQuestionsCorrectAnswered], nil];
labelQuestionsOrder = [[NSArray alloc]initWithObjects:answerWrong, answerCorrect, nil];
legendQuestionsOrder = [[NSArray alloc] initWithObjects:#"Correct answers", #"Wrong answers", nil];
self.dataForQuestionsChart = contentQuestionsArray;
NSLog(#"ContentQuestionsArray: %#", contentQuestionsArray);
//====SET GLOBAL PARAMETERS FOR THE GRAPHs====//
whiteText = [CPTMutableTextStyle textStyle];
whiteText.color = [CPTColor whiteColor];
whiteText.fontSize = 14;
whiteText.fontName = #"Noteworthy-Bold";
[self iPad_matchPieChartConfiguration];
[self iPad_questionsPieChartConfiguration];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
if ( [matchPiePlot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"legendTitleForPieChart: matchPieChart");
if (index < [legendMatchOrder count]) {
return [legendMatchOrder objectAtIndex:index];
}
}
else if ( [matchPiePlot.identifier isEqual:[NSString stringWithFormat:#"questionsPieChart"]] ) {
NSLog(#"legendTitleForPieChart: questionsPieChart");
}
return #"N/A";
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
NSLog(#"numberOfRecordsForPlot:");
if ([plot isKindOfClass:[CPTPieChart class]]) {
return [dataForMatchChart count];
}
else {
return 10; //>>>dummy
}
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSLog(#"numberForPlot:");
NSDecimalNumber *num = nil;
if ([plot isKindOfClass:[CPTPieChart class]]) {
if (index >= [dataForMatchChart count]) {
return nil;
}
if (fieldEnum == CPTPieChartFieldSliceWidth) {
num = [dataForMatchChart objectAtIndex:index];
}
else {
num = (NSDecimalNumber *) [NSDecimalNumber numberWithUnsignedInteger:index];
}
}
return num;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {
NSLog(#"dataLabelForPlot:");
CPTTextLayer *label = nil;
if ( [plot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"dataLabelForPlot: matchPieChart");
label = [[CPTTextLayer alloc] initWithText:[labelMatchOrder objectAtIndex:index]];
CPTMutableTextStyle *textStyle = [label.textStyle mutableCopy];
matchPiePlot.labelOffset = -80;
textStyle.fontName = #"Noteworthy-Bold";
textStyle.color = [CPTColor whiteColor];
textStyle.fontSize = 16;
label.textStyle = textStyle;
return label;
}
else if ( [plot.identifier isEqual:[NSString stringWithFormat:#"matchPieChart"]] ) {
NSLog(#"dataLabelForPlot: MATCH");
}
return label;
}
//====SET COLOR FOR SLICES IN PIE GRAPH====//
-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
// For index = 0
double red1 = 222.0;
double green1 = 184.0;
double blue1 = 135.0;
float alpha1 = 0.5f;
double red2 = 155.0;
double green2 = 00.0;
double blue2 = 0.0;
float alpha2 = 0.3f;
if (index == 0) {
CPTFill *fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:red1 green:green1 blue:blue1 alpha:alpha1]];
return fill;
}
if (index == 1) {
CPTFill *fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:red2 green:green2 blue:blue2 alpha:alpha2]];
return fill;
}
return 0;
}
I am really struggling with this and would appreciate help :-)
Change this line
questionsChartView.hostedGraph = matchPieGraph;
to
questionsChartView.hostedGraph = questionsPieGraph;
Also, check how the two hosting views are laid out within their superview (self.view). Make sure both are visible and positioned correctly.

How to control the line spacing in UILabel

Is it possible to reduce the gap between text, when put in multiple lines in a UILabel? We can set the frame, font size and number of lines. I want to reduce the gap between the two lines in that label.
In Xcode 6 you can do this in the storyboard:
I thought about adding something new to this answer, so I don't feel as bad... Here is a Swift answer:
import Cocoa
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 40
let attrString = NSMutableAttributedString(string: "Swift Answer")
attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
var tableViewCell = NSTableCellView()
tableViewCell.textField.attributedStringValue = attrString
"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels."
See: Set UILabel line spacing
This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.
Starting from iOS 6 you can set an attributed string to the UILabel. Check the following :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];
label.attributedText = attributedString;
The solutions stated here didn't work for me. I found a slightly different way to do it with the iOS 6 NSAttributeString:
myLabel.numberOfLines = 0;
NSString* string = #"String with line one. \n Line two. \n Line three.";
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.minimumLineHeight = 30.f;
style.maximumLineHeight = 30.f;
NSDictionary *attributtes = #{NSParagraphStyleAttributeName : style,};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributtes];
[myLabel sizeToFit];
From Interface Builder (Storyboard/XIB):
Programmatically:
SWift 4
Using label extension
extension UILabel {
// Pass value for any one of both parameters and see result
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
I've made this simple extension that works very well for me:
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = lineHeight
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString()
if (self.attributedText != nil) {
attrString.append( self.attributedText!)
} else {
attrString.append( NSMutableAttributedString(string: self.text!))
attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
}
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
}
Copy this in a file, so then you can use it like this
myLabel.setLineHeight(0.7)
There's an alternative answer now in iOS 6, which is to set attributedText on the label, using an NSAttributedString with the appropriate paragraph styles. See this stack overflow answer for details on line height with NSAttributedString:
Core Text - NSAttributedString line height done right?
Here is a class that subclass UILabel to have line-height property : https://github.com/LemonCake/MSLabel
In Swift and as a function, inspired by DarkDust
// Usage: setTextWithLineSpacing(myEpicUILabel,text:"Hello",lineSpacing:20)
func setTextWithLineSpacing(label:UILabel,text:String,lineSpacing:CGFloat)
{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
label.attributedText = attrString
}
According #Mike 's Answer, reducing the lineHeightMultiple is the key point. Example below, it work well for me:
NSString* text = label.text;
CGFloat textWidth = [text sizeWithAttributes:#{NSFontAttributeName: label.font}].width;
if (textWidth > label.frame.size.width) {
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentCenter;
paragraph.lineSpacing = 1.0f;
paragraph.lineHeightMultiple = 0.75; // Reduce this value !!!
NSMutableAttributedString* attrText = [[NSMutableAttributedString alloc] initWithString:text];
[attrText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, text.length)];
label.attributedText = attrText;
}
SWIFT 3 useful extension for set space between lines more easily :)
extension UILabel
{
func setLineHeight(lineHeight: CGFloat)
{
let text = self.text
if let text = text
{
let attributeString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(NSParagraphStyleAttributeName,
value: style,
range: NSMakeRange(0, text.characters.count))
self.attributedText = attributeString
}
}
}
I've found a way where you can set the real line height (not a factor) and it even renders live in Interface Builder. Just follow the instructions below. Code is written in Swift 4.
Step #1: Create a file named DesignableLabel.swift and insert the following code:
import UIKit
#IBDesignable
class DesignableLabel: UILabel {
#IBInspectable var lineHeight: CGFloat = 20 {
didSet {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString(string: text!)
attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
attributedText = attrString
}
}
}
Step #2: Place a UILabel into a Storyboard/XIB and set its class to DesignableLabel. Wait for your project to build (build must succeed!).
Step 3: Now you should see a new property in the properties pane named "Line Height". Just set the value you like and you should see the results immediately!
Here is a subclass of UILabel that sets lineHeightMultiple and makes sure the intrinsic height is large enough to not cut off text.
#IBDesignable
class Label: UILabel {
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
let padding = (1.0 - lineHeightMultiple) * font.pointSize
size.height += padding
return size
}
override var text: String? {
didSet {
updateAttributedText()
}
}
#IBInspectable var lineHeightMultiple: CGFloat = 1.0 {
didSet {
updateAttributedText()
}
}
private func updateAttributedText() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = lineHeightMultiple
attributedText = NSAttributedString(string: text ?? "", attributes: [
.font: font,
.paragraphStyle: paragraphStyle,
.foregroundColor: textColor
])
invalidateIntrinsicContentSize()
}
}
Swift 3 extension:
import UIKit
extension UILabel {
func setTextWithLineSpacing(text: String, lineHeightMultiply: CGFloat = 1.3) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = lineHeightMultiply
paragraphStyle.alignment = .center
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString
}
}
In Swift 2.0...
Add an extension:
extension UIView {
func attributesWithLineHeight(font: String, color: UIColor, fontSize: CGFloat, kern: Double, lineHeightMultiple: CGFloat) -> [String: NSObject] {
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.lineHeightMultiple = lineHeightMultiple
let attribute = [
NSForegroundColorAttributeName: color,
NSKernAttributeName: kern,
NSFontAttributeName : UIFont(name: font, size: fontSize)!,
NSParagraphStyleAttributeName: titleParagraphStyle
]
return attribute
}
}
Now, just set your UILabel as attributedText:
self.label.attributedText = NSMutableAttributedString(string: "SwiftExample", attributes: attributesWithLineHeight("SourceSans-Regular", color: UIColor.whiteColor(), fontSize: 20, kern: 2.0, lineHeightMultiple: 0.5))
Obviously, I added a bunch of parameters that you may not need. Play around -- feel free to rewrite the method -- I was looking for this on a bunch of different answers so figured I'd post the whole extension in case it helps someone out there... -rab
Swift3 - In a UITextView or UILabel extension, add this function:
I added some code to keep the current attributed text if you are already using attributed strings with the view (instead of overwriting them).
func setLineHeight(_ lineHeight: CGFloat) {
guard let text = self.text, let font = self.font else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = lineHeight
paragraphStyle.alignment = self.textAlignment
var attrString:NSMutableAttributedString
if let attributed = self.attributedText {
attrString = NSMutableAttributedString(attributedString: attributed)
} else {
attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, attrString.length))
}
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
Another answer... If you're passing the string programmatically, you need to pass a attributed string instead a regular string and change it's style.(iOS10)
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:#"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;
This should help with it. You can then assign your label to this custom class within the storyboard and use it's parameters directly within the properties:
open class SpacingLabel : UILabel {
#IBInspectable open var lineHeight:CGFloat = 1 {
didSet {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = self.lineHeight
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString(string: self.text!)
attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
}
}
Swift 4 label extension. Creating NSMutableAttributedString before passing into function in case there are extra attributes required for the attributed text.
extension UILabel {
func setLineHeightMultiple(to height: CGFloat, withAttributedText attributedText: NSMutableAttributedString) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = height
paragraphStyle.alignment = textAlignment
attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length - 1))
self.attributedText = attributedText
}
}
This code worked for me (ios 7 & ios 8 for sure).
_label.numberOfLines=2;
_label.textColor=[UIColor whiteColor];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple=0.5;
paragraphStyle.alignment = NSTextAlignmentCenter;
paragraphStyle.lineSpacing = 1.0;
NSDictionary *nameAttributes=#{
NSParagraphStyleAttributeName : paragraphStyle,
NSBaselineOffsetAttributeName:#2.0
};
NSAttributedString *string=[[NSAttributedString alloc] initWithString:#"22m\nago" attributes:nameAttributes];
_label.attributedText=string;
Here is my solution in swift. The subclass should work for both attributedText and text property and for characterSpacing + lineSpacing. It retains the spacing if a new string or attributedString is set.
open class UHBCustomLabel : UILabel {
#IBInspectable open var characterSpacing:CGFloat = 1 {
didSet {
updateWithSpacing()
}
}
#IBInspectable open var lines_spacing:CGFloat = -1 {
didSet {
updateWithSpacing()
}
}
open override var text: String? {
set {
super.text = newValue
updateWithSpacing()
}
get {
return super.text
}
}
open override var attributedText: NSAttributedString? {
set {
super.attributedText = newValue
updateWithSpacing()
}
get {
return super.attributedText
}
}
func updateWithSpacing() {
let attributedString = self.attributedText == nil ? NSMutableAttributedString(string: self.text ?? "") : NSMutableAttributedString(attributedString: attributedText!)
attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
if lines_spacing >= 0 {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lines_spacing
paragraphStyle.alignment = textAlignment
attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
}
super.attributedText = attributedString
}
}