self.textView.textContainer.lineFragmentPadding = 0;
self.textView.textContainerInset = UIEdgeInsetsZero;
Get City name from Latitude and Longtiude
- (void) getAddressFromLatLon:(CLLocation *)bestLocation
{
NSLog(@"%f %f", bestLocation.coordinate.latitude, bestLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:bestLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);
NSLog(@"locality %@",placemark.locality);
NSLog(@"postalCode %@",placemark.postalCode);
}];
}
{
NSLog(@"%f %f", bestLocation.coordinate.latitude, bestLocation.coordinate.longitude);
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:bestLocation
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);
NSLog(@"locality %@",placemark.locality);
NSLog(@"postalCode %@",placemark.postalCode);
}];
}
Labels:
city,
CLLocation,
country,
iphone SDK,
location,
postal code
Generate JSON string from NSDictionary
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
Labels:
convert,
iphone SDK,
jsonstring
Change UITextfield Placeholder Color
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
Labels:
iphone SDK,
placeholder,
textfield
Check iOS version
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
// here you go with iOS 7
}
// here you go with iOS 7
}
Labels:
device,
iphone SDK
ModalViewController transparent background
[viewController setModalPresentationStyle:UIModalPresentationOverCurrentContext];
Labels:
iphone SDK,
present,
transparant,
transparent
Check if the entered text uses only English letters
NSCharacterSet* tSet = [NSCharacterSet characterSetWithCharactersInString:
@"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSCharacterSet* invSet = [tSet invertedSet];
NSString* legalS = @"abcdA1";
NSString* illegalS = @"asvéq1";
if ([legalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(legalS); // not printed
if ([illegalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(illegalS); // printed
@"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSCharacterSet* invSet = [tSet invertedSet];
NSString* legalS = @"abcdA1";
NSString* illegalS = @"asvéq1";
if ([legalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(legalS); // not printed
if ([illegalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(illegalS); // printed
Labels:
compare,
iphone SDK,
search,
string
Hide UINavigationBar 1px Bottom Line
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init]
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
Labels:
iphone SDK,
navbar,
navigationbar,
remove
Android Hide App Icon on Launcher
On AndroidManifest.xml remove:
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LAUNCHER" />
iOS Air print for UIwebview
UIPrintInfo *pi = [UIPrintInfo printInfo];
pi.outputType = UIPrintInfoOutputGeneral;
pi.jobName = webView.request.URL.absoluteString;
pi.orientation = UIPrintInfoOrientationPortrait;
pi.duplex = UIPrintInfoDuplexLongEdge;
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.printInfo = pi;
pic.showsPageRange = YES;
pic.printFormatter = webView.viewPrintFormatter;
[pic presentAnimated:YES completionHandler:^(UIPrintInteractionController *pic2, BOOL completed, NSError *error) {
// indicate done or error
}];
pi.outputType = UIPrintInfoOutputGeneral;
pi.jobName = webView.request.URL.absoluteString;
pi.orientation = UIPrintInfoOrientationPortrait;
pi.duplex = UIPrintInfoDuplexLongEdge;
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.printInfo = pi;
pic.showsPageRange = YES;
pic.printFormatter = webView.viewPrintFormatter;
[pic presentAnimated:YES completionHandler:^(UIPrintInteractionController *pic2, BOOL completed, NSError *error) {
// indicate done or error
}];
Labels:
airprint,
iphone SDK,
print,
webview
Linking UIPageControl to UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = self.scrollView.frame.size.width; // you need to have a **iVar** with getter for scrollView
float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
self.pageControl.currentPage = page; // you need to have a **iVar** with getter for pageControl
}
Don't forget to set the UIScrollView's delegate
CGFloat pageWidth = self.scrollView.frame.size.width; // you need to have a **iVar** with getter for scrollView
float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
self.pageControl.currentPage = page; // you need to have a **iVar** with getter for pageControl
}
Don't forget to set the UIScrollView's delegate
Labels:
connect,
iphone SDK,
page control,
scrollview
Get Text Position in TextView
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView
{
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end]];
CGRect rect = [textView firstRectForRange:textRange];
return [textView convertRect:rect fromView:textView.textInputView];
}
{
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end]];
CGRect rect = [textView firstRectForRange:textRange];
return [textView convertRect:rect fromView:textView.textInputView];
}
Labels:
find,
iphone SDK,
search
Run project with specified localization
Go to the menu Product > Edit Scheme. Then, in your run configuration switch to the Arguments tab and create a new one to be passed on launch. Add
-AppleLanguages "(Japanese)"
or
-AppleLanguages "(Ja)"
Labels:
iphone SDK,
language,
test localization
Get UITextView content size in iOS7
- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
{
// This is the code for iOS 7. contentSize no longer returns the correct value, so
// we have to calculate it.
//
// This is partly borrowed from HPGrowingTextView, but I've replaced the
// magic fudge factors with the calculated values (having worked out where
// they came from)
CGRect frame = textView.bounds;
// Take account of the padding added around the text.
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:@"\n"])
{
textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
}
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
{
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
{
// This is the code for iOS 7. contentSize no longer returns the correct value, so
// we have to calculate it.
//
// This is partly borrowed from HPGrowingTextView, but I've replaced the
// magic fudge factors with the calculated values (having worked out where
// they came from)
CGRect frame = textView.bounds;
// Take account of the padding added around the text.
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:@"\n"])
{
textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
}
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
Labels:
height,
iphone SDK,
textview
Making the iPhone vibrate
There are two seemingly similar functions that take a parameter kSystemSoundID_Vibrate:
1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Both the functions vibrate the iPhone. But when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function on the other hand does nothing on unsupported devices. So if you are going to vibrate the device continuously, as a alert, common sense says, use function 2.
Don't forget to add:
#import <AudioToolbox/AudioServices.h>
1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Both the functions vibrate the iPhone. But when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function on the other hand does nothing on unsupported devices. So if you are going to vibrate the device continuously, as a alert, common sense says, use function 2.
Don't forget to add:
#import <AudioToolbox/AudioServices.h>
Labels:
iphone SDK,
vibrate
Keep iPhone from sleeping
To stop your app from timing out and going to sleep you can use:
[UIApplication sharedApplication].idleTimerDisabled = YES;
This will, obviously, disable the idle timer and stop your iphone from automatically going into sleep mode.
Note: To re-enable the idle timer when you no longer need to keep the phone awake (generally after that view has been removed) using:
[UIApplication sharedApplication].idleTimerDisabled = NO;
[UIApplication sharedApplication].idleTimerDisabled = YES;
This will, obviously, disable the idle timer and stop your iphone from automatically going into sleep mode.
Note: To re-enable the idle timer when you no longer need to keep the phone awake (generally after that view has been removed) using:
[UIApplication sharedApplication].idleTimerDisabled = NO;
Labels:
iphone SDK,
sleep
Open URL in Browser for Windows Phone 8
using System;
using Microsoft.Phone.Tasks;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
using Microsoft.Phone.Tasks;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://msdn.microsoft.com", UriKind.Absolute);
webBrowserTask.Show();
Labels:
link,
window phone
Get Windows Phone Screen Size and Scale Factor
using System.Windows;
public void GetScreenResolution()
{
double w = Application.Current.Host.Content.ActualWidth;
double h = Application.Current.Host.Content.ActualHeight;
int scale = Application.Current.Host.Content.ScaleFactor;
}
The following is an overview of the current characteristics of all these properties:
public void GetScreenResolution()
{
double w = Application.Current.Host.Content.ActualWidth;
double h = Application.Current.Host.Content.ActualHeight;
int scale = Application.Current.Host.Content.ScaleFactor;
}
The following is an overview of the current characteristics of all these properties:
| WVGA | HD | WXGA | |
| ActualWidth | 480 | 480 | 480 |
| ActualHeight | 800 | 853 | 800 |
| ScaleFactor (%) | 100 | 150 | 160 |
| Resulting Size (Width/Height x Scale) | 480x800 | 720x1280 | 768x1280 |
Debug or Print Log in Windows Phone 8
System.Diagnostics.Debug.WriteLine("")
You can debug the native code in the windows phone Runtime Component by selecting the native debug engine for the UI Task. in this case you will also get the debug output.
to select the native debug engine for UI Task
1. Go to debug property page by right clicking on the project and selecting the "properties" menu followed by selecting the "Debug" tab.
2. Under the "UI Task" there is a drop down. select "Native Only"
You can debug the native code in the windows phone Runtime Component by selecting the native debug engine for the UI Task. in this case you will also get the debug output.
to select the native debug engine for UI Task
1. Go to debug property page by right clicking on the project and selecting the "properties" menu followed by selecting the "Debug" tab.
2. Under the "UI Task" there is a drop down. select "Native Only"
Labels:
debug,
log,
window phone
Dismiss UIAlertViews or UIActionSheet When Enter Background State
- (void)checkViews:(NSArray *)subviews {
Class AVClass = [UIAlertView class];
Class ASClass = [UIActionSheet class];
for (UIView * subview in subviews){
if ([subview isKindOfClass:AVClass]){
[(UIAlertView *)subview dismissWithClickedButtonIndex:[(UIAlertView *)subview cancelButtonIndex] animated:NO];
} else if ([subview isKindOfClass:ASClass]){
[(UIActionSheet *)subview dismissWithClickedButtonIndex:[(UIActionSheet *)subview cancelButtonIndex] animated:NO];
} else {
[self checkViews:subview.subviews];
}
}
}
Calling it from the applicationDidEnterBackground procedure
[self checkViews:application.windows];
Class AVClass = [UIAlertView class];
Class ASClass = [UIActionSheet class];
for (UIView * subview in subviews){
if ([subview isKindOfClass:AVClass]){
[(UIAlertView *)subview dismissWithClickedButtonIndex:[(UIAlertView *)subview cancelButtonIndex] animated:NO];
} else if ([subview isKindOfClass:ASClass]){
[(UIActionSheet *)subview dismissWithClickedButtonIndex:[(UIActionSheet *)subview cancelButtonIndex] animated:NO];
} else {
[self checkViews:subview.subviews];
}
}
}
Calling it from the applicationDidEnterBackground procedure
[self checkViews:application.windows];
Subscribe to:
Posts (Atom)
