I'm a novice and recreational programmer. I am trying to create an app for iOS that populates the text from my UITextFields. I have 3 the actionField, impactField, and result Field. I'd like for each to have their own line, if possible.
I looked at a similar answer, but it was not any help for me. Does anyone have any tutorials or advice?
- (IBAction)backgroundTap: (id)sender {
[self.actionField resignFirstResponder];
[self.impactField resignFirstResponder];
[self.resultField resignFirstResponder];
}
- (IBAction)sendBullet:(id)sender {
NSString *emailTitle = #"Email";
NSString *messageBody = #"Title";
NSArray *toRecipients = [NSArray arrayWithObject:#"email"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
MHinton,
Before you proceed, you should take a look at HTML syntax, there are hundreds of thousands of tutorials out there since this has been around for decades. It's fairly easy to pick up. You can start HERE
NOTE It's best to test HTML emails on a device as the simulator can be kind of wonky with the MFMailComposeViewController
Secondly, grabbing the text from a text view or other forms of strings is fairly easy, again, thousands of tutorials out there. Specifically for Obj C you do it as follows :
1) Create an outlet for your textfields
#interface YourViewController: UIViewController
#property (nonatomic, retain) IBOutlet UITextField *actionField
#end
2) Then you can reference it anywhere in your implementation file (.m) like this :
NSString *emailMessageBody = self.actionField.text;
DISPLAYING TEXT IN HTML FORMAT FOR EMAILS
Creating an HTML formatted email is relatively easy as long as you spend about 15 minutes learning HTML syntax.
If you want to insert your UITextFields in different lines you implement the HTML equivalent to line break (or pressing the enter button): <br>
So an example string to pass in the MFMailComposeViewController will look like this:
NSString *emailMessageBody = [NSString stringWithFormat:#"The retrieved text from actionField is : <br><strong><font color=\"red\">'%#'</font><br></strong><br> The retrieved text from impactField is : <br>%#<br> The retrieved text from resultField is : <br>%#<br>", self.actionField.text, self.impactField.text, self.resultField.text];
Your options are limitless here, as long as you know HTML syntax. So whats going on here?
<br> creates the line break
<strong> creates a bold style text and to end the format you place </strong> after the last word you want bold faced
<font> self explanatory; you have to end this style format as well.
You call it in the MFMailComposeViewController per usual, however you must explicitly set the email to HTML so all the HTML tags can be stripped from formatting and so it doesn't display it as plain text.
[mc setMessageBody:emailMessageBody isHTML:YES];
Other commonly used HTML tags are :
<style> for formatting
<p> for paragraphs
<h1> for headers
<mark> for highlighting
<small> for small text
<i> or <em> for italics or emphasized
Refer to the link above for more HTML tags
SWIFT SYNTAX
var emailMessageBody = NSString(format:"The retrieved text from actionField is : <br><strong><font color=\"red\">'%#'</font><br></strong><br> The retrieved text from impactField is : <br>%#<br> The retrieved text from resultField is : <br>%#<br>", actionField.text, impactField.text, resultField.text) as String
mailComposerVC.setMessageBody(emailMessageBody, isHTML: true)
All you need to do is build a string from the text fields:
NSString *messageBody = [NSString stringWithFormat:#"Action: %#\nImpact: %#\nResult: %#", self.actionField.text, self.impactField.text, self.resultField.text];
Update the format string as needed. What I present here is just one example.
The \n is a special value in a string that means "newline". This means the string I show will consist of three lines of text.
Related
Here is my problem.
I have a ViewController in which there is a label with a text and I want to change the color of some of the words in that sentence.
The string is an NSLocalizedString which is written in different languages and changes based on the user system language.
self.welcomeMessageLabel.text = NSLocalizedString(#"welcome_message", nil);
This is the result that I want to achieve.
How can I color part of the text?
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_welcomeMessageLabel.attributedText = [self attributedString1];
}
- (NSAttributedString *)attributedString1 {
NSString *string = #"Ti abbiamo inviato un link all'inndirizzo email che";
NSString *substring1 = #"link";
NSString *substring2 = #"email";
// NSString *string = NSLocalizedString(#"welcome_message", nil);
// NSString *substring1 = NSLocalizedString(#"welcome_message_substring1", nil);
// NSString *substring2 = NSLocalizedString(#"welcome_message_substring2", nil);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: string];
NSDictionary *attributes = #{NSForegroundColorAttributeName: [UIColor orangeColor]};
[attributedString
replaceCharactersInRange:[string rangeOfString:substring1]
withAttributedString:[[NSAttributedString alloc] initWithString: substring1 attributes:attributes]
];
[attributedString
replaceCharactersInRange:[string rangeOfString:substring2]
withAttributedString:[[NSAttributedString alloc] initWithString: substring2 attributes:attributes]
];
return attributedString;
}
#end
NSLocalizedString(#"welcome_message", nil) returns a NSString.
Let's clarify, it's just a "suite of characters", there is no notion of bold/colors, italic, offsets, etc.
And to show different characters with different rendering (colors, boldness, etc.) you need to use NSAttributedString
Since it's only a suite of characters, you need to find which elements need to have a different rendering. To do so, you can use tags, like HTML, Markdown, BBCode tags.
Sample for the part, and I'll simplify focusing only in bold:
//Initial text
...un link all'indirizzo...
// With BBCode tag
...un [b]link[/b] all'indirizzo...
// With HTML tag
...un <b>link</b> all'indirizzo...
// With Markdown tag
...un **link** all'indirizzo...
// With custom tag
...un {link} all'indirizzo...
Put that new value in your strings file.
If you use HTML, there is a built-in init method for that. See related question: Convert HTML to NSAttributedString in iOS
For the other ones, you can either use a third party lib parser, or parse them yourself. You can use NSRegularExpression, NSScanner, etc... and then apply the target effect to the correct range.
I try to send e-mail from my IOS app but it does not work. I have tried lots of different tutorials, test it on a real iPhone. I have implemented MFMailComposeViewControllerDelegate, imported MessageUI / MessageUI.h in the h file. When the message is opened the subject is there but not the message itself and not to whom the message should be sent to(Recipient). Both are empty, and the message can not be sent. I do not understand what the problem is I have followed 10 different tutorials but none works. I work in Xcode 7 (objective c).
You have to add the recipients in the recipient array and pass it to MFMailComposeViewController. Like this:
if([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController* mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"Test Subject"];
[mail setMessageBody:#"Stannis Baratheon is the one true King....Also this is a test email" isHTML:NO];
NSArray *arrayOfRecepients = [[NSArray alloc] initWithObjects: #"test#gmail.com",#"test#yahoo.com",nil];//Add as many email addresses as you want. For single email, add only one email in this array
[mail setToRecipients:arrayOfRecepients];
[self presentViewController:mail animated:YES completion:NULL];
}
I am assuming that you are not adding recipients correctly. I am waiting for your response to Russell's comment to show us your code to correctly determine what is wrong with your code. I will then update the answer if need be.
When i restarded my phone it worked, so if this happends try to restart your IOS device
I am using an app to lock, unlock, and open the trunk of my car. The only problem is that I can't figure out how to modify the Xcode project so there are 3 buttons. Basically right now if I type "U" then enter- the car unlocks, "L" then enter- the car locks, and "T" then enter- the trunk opens. I want to add three buttons that simulate these three things and eliminate the typing all together. If you want to see my adruino or xcode project code I can upload those. I have put some code about the text box below.
BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text = textField.text;
NSNumber *form = [NSNumber numberWithBool:NO];
NSString *s;
NSData *d;
if (text.length > 16)
s = [text substringToIndex:16];
else
s = text;
d = [s dataUsingEncoding:NSUTF8StringEncoding];
if (bleShield.activePeripheral.state == CBPeripheralStateConnected) {
[bleShield write:d];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:text, TEXT_STR, form, FORM, nil];
[tableData addObject:dict];
[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
NSLog(#"%f", _tableView.contentOffset.y);
[self.tableView reloadData];
}
textField.text = #"";
return YES;
Thanks for the help!
Your view controller probably has a textFieldShouldReturn method which is taking the string value from the text field and building a parameter to a call that initiates sending the command. If not this method then perhaps its action method linked to the text field.
You'll need to duplicate parts of that code into a method that receives a string parameter instead of taking it from the text field, say named sendLockCommand:(NSString *)commandString (assuming you're coding in Objective-C, also like that repo).
Make action methods for your buttons, something like lockDoors, unlockDoors, openTrunk, in each call [self sendLockCommand:#"L"], each with the appropriate string. Wire up the buttons to those actions and you're good to go.
I started creating all elements programmatically and I repeat most of the code for styling the fields (e.g. borderStyle, keyboardType, keyboardAppearance, spellCheckingType, etc.).
What is the most acceptable way of doing this from one place?
Analogue would be CSS - I would define the general styles in one place, and all generated elements would use them automatically.
Thanks!
If I kept wanting UITextFields with a certain setup, my preferred approach would be to add a factory method to UITextField:
#implementation UITextField (DHFactory)
+ (instancetype)dh_textField {
UITextField *textField = [[self alloc] init];
[textField setKeyboardAppearance:UIKeyboardAppearanceAlert];
[textField setSpellCheckingType:UITextSpellCheckingTypeNo];
return textField;
}
#end
I prefixed the category method name, following the advice in Apple’s Programming with Objective-C.
I am using TWTweetComposeViewController, when available, to send tweets from inside my iOS app. I pre-populate the view controller with boilerplate text, then let the user modify and send at their discretion. It works great for the most part. Distilled down, it looks like this (with body pointing at a valid NSString):
if (NSClassFromString(#"TWTweetComposeViewController")) {
TWTweetComposeViewController *iOS5twitter = [[TWTweetComposeViewController alloc] init];
[iOS5twitter setInitialText:body];
iOS5twitter.completionHandler = ^(TWTweetComposeViewControllerResult result)
{
[self.viewController dismissViewControllerAnimated:YES completion:nil];
};
[self.viewController presentViewController:iOS5twitter animated:YES completion:nil];
[iOS5twitter release];
}
else {
/* Do something else when the framework is missing */
}
Now if body is too long, i.e., more than 140 characters, the resulting tweet view is empty of any text at all, character countdown set to 140. I might have expected truncation in this case, although it does not appear to be documented in the Class Reference one way or the other what happens when the initial text is too long, but I can accept that I have to do the truncation to maximum tweet length before passing to setInitialText.
What I don't understand is that certain messages which are shorter than 140 characters also produce the empty tweet view.
Initially I saw what seemed to be a perfectly valid string with 139 characters failing. I noticed that shortening the string made it work. But after a great deal of experimenting, I also noticed that replacing a URL which happened to appear inside the text with random text of the same length made it work. In other words, the URL itself is causing a problem.
So I thought maybe there was something weird about the URL I was using, but I distilled it down to this. This one works:
NSString *body = #"............................................................................................................................................";
while this does not
NSString *body = #"............http://a........................................................................................................................";
Observations:
They are both 140 characters long (and report that way in the console with [body length]). The only difference is the presence of something vaguely URL-like embedded in the middle of the second one.
The position of the URL within the string does not seem to matter, but if I change any one of those non-period characters to a period (thus making it not like a URL anymore), it ceases to be broken.
If I shorten the broken one, shaving 14 periods off the end, it works. That is, this particular URL embedded in periods for a total length of 126 characters is fine. 127 or larger is broken. Not clear how, or if, this relates to the length of the URL itself.
Anybody ever seen something like this? Any idea what is going on? Am I doing something wrong, or is the iOS Twitter Framework just broken?
I have run into the exact same problem. It is a known bug in the Twitter framework and is being tracked.
Please see this discussion on dev.twitter.com https://dev.twitter.com/discussions/5024
(I would have posted that as a comment rather than an answer if I could, but I don't have sufficient SO credibility so thought I'd add the below observations as well in case they are of interest).
When just adding text without URLs, the character count works as expected.
Adding a URL with the addURL: method causes 21 characters of the tweet to be used (20 for URL plus a space). Adding the URL in the initial text causes 20 chars to be used for the URL.
When including a single URL (using either method) the framework fails when the total character count exceeds 138 (e.g. 20 for URL + space + 117 chars of initial text) thus losing 2 characters. With just one URL the order of setting the initial text and then adding the URL with addURL: does not make a difference.
When adding 2 URls, it fails when the total character count exceeds 113 this losing 27 characters!
However, with 2 or more, if you add the URLs BEFORE setting the initial text, it fails with a total count of 136. So 2 chars are lost per URL again.
Summary/Workaround - if just including 1 URL then adding it in the initial text will give you one extra character than using the addURL: method, but you will still be short 2 characters overall. If adding 2 or more URLs using addURL: then add them before the initial text, but until the bug is fixed, you will still lose 2 chars per URL.
I have filed a radar, but according to this Can I browse other people's (Apple) bug reports?, the more times a bug is reported the higher priority it is given, so it is worth others filing it as well to increase it's priority.
This seems to be a bug; I sure wish there was a way to directly ask TWTweetComposeViewController how much space is left. Fortunately there is an indirect way to ask. setInitialText: returns NO if the message is too long, so what I've done is brute-force it, chopping off five characters at a time until it returns YES:
- (void)tweetURL:(NSString *)url title:(NSString *)title {
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
NSString *format = #"“%#” %# /via #DesignSceneApp";
NSString *message = [NSString stringWithFormat:format, title, url]
NSUInteger idx = title.length;
while (![twitter setInitialText:message]) {
idx -= 5;
if (idx > 5) {
message = [NSString stringWithFormat:format,
[NSString stringWithFormat:#"%#…", [title substringToIndex:idx]],
url
];
} else {
// Give up on the title.
message = [NSString stringWithFormat:#"%# /via #DesignSceneApp", url];
[twitter setInitialText:message];
break;
}
}
[self presentViewController:twitter animated:YES completion:nil];
}
I know, it's ugly, right? But at least it allows me to get a reasonable approximation of the max length, so that I truncate no more of the link title than I need to.
Some code excerpt for automatic message trimming:
[tweetSheet addURL:[NSURL URLWithString:#"http://some.nice.url/"]];
if (![tweetSheet setInitialText:message]) {
NSUInteger messageMaxIndex = [message length];
while (messageMaxIndex > 0 && ![tweetSheet setInitialText:[NSString stringWithFormat: #"%# ...", message]]) {
--messageMaxIndex;
message = [message substringToIndex:messageMaxIndex];
};
}
Instead of
[iOS5twitter setInitialText:#"My url is http://something.com. No idea why it is not working"];
Try this
NSString *yourUrlString = #"http://something.com";
NSString *msg= #"My url is %#. No idea why it is not working";
NSString *defaultMessage = [NSString stringWithFormat:msg,yourUrlString];
[iOS5twitter setInitialText:defaultMessage];
I have no idea why it is so but I just faced this problem and tried it and it is working for me.
I had similar problem. Twitter controller doesn't display tweets, that are too long. You can take a substring of a tweet by cutting down to 140 symbols:
[tweetView setInitialText:[self.textToExport substringToIndex:140]];
NSLog(#"tweetView.initialText:%#", [self.textToExport substringToIndex:140]);
try this code
- (IBAction)DeveloperTwitter:(id)sender {
NSString* tweet = #"some tweet goes here..";
if ([TWTweetComposeViewController canSendTweet]) {
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
[twitter setInitialText:tweet];
[self presentViewController:twitter animated:YES completion:nil];
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if(res == TWTweetComposeViewControllerResultDone) {
// sent ...
}
[self dismissModalViewControllerAnimated:YES];
};
}
else {
tweet = [NSString stringWithFormat:#"%#%#", #"http://twitter.com/home?status=", tweet];
tweet = [tweet stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: tweet]];
}
tweet=nil;
}