2
0
mirror of synced 2025-02-23 23:08:14 +00:00

example/ivy/ios: format code according to Google style guide

Change-Id: I4cef2b60756b3318c123b832bcdb719d2d45fadc
Reviewed-on: https://go-review.googlesource.com/c/mobile/+/360607
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Hyang-Ah Hana Kim <hyangah@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
This commit is contained in:
robaho 2021-11-01 22:30:14 -05:00 committed by Hyang-Ah Hana Kim
parent 2ab7fee9df
commit e68c98865f
8 changed files with 334 additions and 389 deletions

View File

@ -3,12 +3,12 @@
// license that can be found in the LICENSE file.
#import <WebKit/WebKit.h>
#import "Suggestion.h"
#import "IvyController.h"
#import "Suggestion.h"
@interface AppDelegate
: UIResponder <UIApplicationDelegate, UITextFieldDelegate, WKUIDelegate>
@interface AppDelegate : UIResponder <UIApplicationDelegate, UITextFieldDelegate, WKUIDelegate>
@property (strong, nonatomic) UIWindow *window;
@property(strong, nonatomic) UIWindow *window;
@end

View File

@ -12,29 +12,24 @@
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application
{
- (void)applicationWillTerminate:(UIApplication *)application {
}
@end

View File

@ -8,3 +8,4 @@
@interface DocsController : UIViewController
@end

View File

@ -6,36 +6,37 @@
#import "mobile/Mobile.h"
@interface DocsController () {
WKWebView *webView;
WKWebView *webView;
}
@end
@implementation DocsController
- (void)viewDidLoad
{
[super viewDidLoad];
webView = (WKWebView *)[self.view viewWithTag:11];
NSString *helpHTML = MobileHelp();
NSRange r = [helpHTML rangeOfString:@"<head>"];
NSString *html = [helpHTML substringToIndex:r.location];
- (void)viewDidLoad {
[super viewDidLoad];
webView = (WKWebView *)[self.view viewWithTag:11];
NSString *helpHTML = MobileHelp();
NSRange r = [helpHTML rangeOfString:@"<head>"];
NSString *html = [helpHTML substringToIndex:r.location];
// With the following meta tag, WKWebView displays the fonts more nicely.
NSString *meta = @"<meta name='viewport' \
content='width=device-width, initial-scale=1.0, maximum-scale=1.0, \
minimum-scale=1.0, user-scalable=no'>";
// With the following meta tag, WKWebView displays the fonts more nicely.
NSString *meta = @"<meta name='viewport' \
content='width=device-width, "
@"initial-scale=1.0, maximum-scale=1.0, \
minimum-scale=1.0, "
@"user-scalable=no'>";
html = [html stringByAppendingString:@"<head>"];
html = [html stringByAppendingString:meta];
html = [html stringByAppendingString:[helpHTML substringFromIndex:r.location]];
html = [html stringByAppendingString:@"<head>"];
html = [html stringByAppendingString:meta];
html = [html stringByAppendingString:[helpHTML substringFromIndex:r.location]];
[webView loadHTMLString:html baseURL:NULL];
[webView loadHTMLString:html baseURL:NULL];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end

View File

@ -2,25 +2,24 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <WebKit/WebKit.h>
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import "Suggestion.h"
// IvyController displays the main app view.
@interface IvyController
: UIViewController <UITextFieldDelegate, WKUIDelegate,
SuggestionDelegate>
@interface IvyController : UIViewController <UITextFieldDelegate, WKUIDelegate, SuggestionDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
// A text input field coupled to an output "tape", rendered with a WKWebView.
@property (weak, nonatomic) IBOutlet UITextField *input;
@property (strong, nonatomic) Suggestion *suggestionView;
@property (weak, nonatomic) IBOutlet WKWebView *tape;
@property (weak, nonatomic) IBOutlet UIButton *okButton;
@property(weak, nonatomic) IBOutlet UITextField *input;
@property(strong, nonatomic) Suggestion *suggestionView;
@property(weak, nonatomic) IBOutlet WKWebView *tape;
@property(weak, nonatomic) IBOutlet UIButton *okButton;
- (IBAction)clear:(id)sender;
- (IBAction)demo:(id)sender;
- (IBAction)okPressed:(id)sender;
@end

View File

@ -10,225 +10,207 @@
@end
@implementation IvyController {
NSArray *demo_lines;
int demo_index;
NSArray *demo_lines;
int demo_index;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.input.delegate = self;
self.input.autocorrectionType = UITextAutocorrectionTypeNo;
self.input.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
self.suggestionView = [[Suggestion alloc] init];
self.suggestionView.delegate = self;
self.tape.UIDelegate = self;
self->demo_lines=NULL;
[self.okButton setTitle:@"" forState:UIControlStateNormal];
[self.okButton setHidden:TRUE];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(textDidChange:)
name:UITextFieldTextDidChangeNotification
object:self.input];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
- (void)viewDidLoad {
[super viewDidLoad];
[self.input becomeFirstResponder];
[self clear:NULL];
self.input.delegate = self;
self.input.autocorrectionType = UITextAutocorrectionTypeNo;
self.input.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
self.suggestionView = [[Suggestion alloc] init];
self.suggestionView.delegate = self;
self.tape.UIDelegate = self;
self->demo_lines = NULL;
[self.okButton setTitle:@"" forState:UIControlStateNormal];
[self.okButton setHidden:TRUE];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textDidChange:)
name:UITextFieldTextDidChangeNotification
object:self.input];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[self.input becomeFirstResponder];
[self clear:NULL];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = self.suggestionView;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
[textField reloadInputViews];
}
return YES;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = self.suggestionView;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
[textField reloadInputViews];
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = nil;
[textField reloadInputViews];
}
return YES;
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = nil;
[textField reloadInputViews];
}
return YES;
}
- (void)textDidChange:(NSNotification *)notif
{
[self.suggestionView suggestFor:self.input.text];
- (void)textDidChange:(NSNotification *)notif {
[self.suggestionView suggestFor:self.input.text];
}
- (void)suggestionReplace:(NSString *)text
{
self.input.text = text;
[self.suggestionView suggestFor:text];
- (void)suggestionReplace:(NSString *)text {
self.input.text = text;
[self.suggestionView suggestFor:text];
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
// Move the input text field up, as the keyboard has taken some of the screen.
NSDictionary *info = [aNotification userInfo];
CGRect kbFrame =
[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration =
[info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
- (void)keyboardWillShow:(NSNotification *)aNotification {
// Move the input text field up, as the keyboard has taken some of the screen.
NSDictionary *info = [aNotification userInfo];
CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
self.bottomConstraint.constant = 0 - kbFrame.size.height;
[self.view layoutIfNeeded];
}
completion:^(BOOL finished) {
}
completion:^(BOOL finished) {
[self scrollTapeToBottom];
}];
}];
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
// Move the input text field back down.
NSDictionary *info = [aNotification userInfo];
NSNumber *duration =
[info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
- (void)keyboardWillHide:(NSNotification *)aNotification {
// Move the input text field back down.
NSDictionary *info = [aNotification userInfo];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
int offset = self.input.inputAccessoryView != NULL ? self.suggestionView.frame.size.height : 0;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
int offset = self.input.inputAccessoryView != NULL ? self.suggestionView.frame.size.height : 0;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
self.bottomConstraint.constant = 0 - offset;
[self.view layoutIfNeeded];
}
completion:^(BOOL finished) {
}
completion:^(BOOL finished) {
[self scrollTapeToBottom];
}];
}];
}
- (void)enterPressed
{
NSString *text = self.input.text;
if ([text isEqual:@""]){
if(self->demo_lines==NULL){
return;
}
while (demo_index < self->demo_lines.count) {
NSString *line = self->demo_lines[self->demo_index++];
if([line hasPrefix:@"#"]) {
[self appendTape:line tag:@"comment"];
} else {
self.input.text = line;
break;
}
}
} else if (self->demo_lines!=NULL && [text isEqual:@"quit"]) {
[self unloadDemo];
} else {
[self appendTape:text tag:@"expr"];
NSString *expr = [text stringByAppendingString:@"\n"];
NSError *err;
NSString *result = MobileEval(expr, &err);
if (err != nil) {
result = err.description;
}
result = [result
stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
result =
[result stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
result =
[result stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
NSMutableArray *lines =
(NSMutableArray *)[result componentsSeparatedByString:@"\n"];
for (NSMutableString *line in lines) {
if ([line hasPrefix:@"#"])
[self appendTape:line tag:@"comment"];
else
[self appendTape:line tag:@"result"];
}
self.input.text = @"";
- (void)enterPressed {
NSString *text = self.input.text;
if ([text isEqual:@""]) {
if (self->demo_lines == NULL) {
return;
}
while (demo_index < self->demo_lines.count) {
NSString *line = self->demo_lines[self->demo_index++];
if ([line hasPrefix:@"#"]) {
[self appendTape:line tag:@"comment"];
} else {
self.input.text = line;
break;
}
}
} else if (self->demo_lines != NULL && [text isEqual:@"quit"]) {
[self unloadDemo];
} else {
[self appendTape:text tag:@"expr"];
NSString *expr = [text stringByAppendingString:@"\n"];
NSError *err;
NSString *result = MobileEval(expr, &err);
if (err != nil) {
result = err.description;
}
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
result = [result stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
result = [result stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
NSMutableArray *lines = (NSMutableArray *)[result componentsSeparatedByString:@"\n"];
for (NSMutableString *line in lines) {
if ([line hasPrefix:@"#"])
[self appendTape:line tag:@"comment"];
else
[self appendTape:line tag:@"result"];
}
[self.input becomeFirstResponder];
}
- (void)scrollTapeToBottom
{
NSString *scroll = @"window.scrollBy(0, document.body.offsetHeight);";
[self.tape evaluateJavaScript:scroll completionHandler:nil];
}
- (void)appendTape:(NSString *)text tag:(NSString *)tag
{
NSString *injectSrc = @"appendDiv('%@','%@');";
NSString *runToInject = [NSString stringWithFormat:injectSrc, text, tag];
[self.tape evaluateJavaScript:runToInject completionHandler:nil];
[self scrollTapeToBottom];
}
- (void)loadDemo
{
[self.okButton setHidden:FALSE];
NSString *text = DemoText();
self->demo_lines = [text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
self->demo_index = 0;
self.input.text = @"";
self.input.enablesReturnKeyAutomatically=TRUE;
[self enterPressed];
}
[self.input becomeFirstResponder];
}
- (void)unloadDemo
{
[self.okButton setHidden:TRUE];
self.input.enablesReturnKeyAutomatically=FALSE;
self->demo_lines=NULL;
self.input.text = @"";
- (void)scrollTapeToBottom {
NSString *scroll = @"window.scrollBy(0, document.body.offsetHeight);";
[self.tape evaluateJavaScript:scroll completionHandler:nil];
}
- (void)appendTape:(NSString *)text tag:(NSString *)tag {
NSString *injectSrc = @"appendDiv('%@','%@');";
NSString *runToInject = [NSString stringWithFormat:injectSrc, text, tag];
[self.tape evaluateJavaScript:runToInject completionHandler:nil];
[self scrollTapeToBottom];
}
- (void)loadDemo {
[self.okButton setHidden:FALSE];
NSString *text = DemoText();
self->demo_lines =
[text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
self->demo_index = 0;
self.input.text = @"";
self.input.enablesReturnKeyAutomatically = TRUE;
[self enterPressed];
}
- (void)unloadDemo {
[self.okButton setHidden:TRUE];
self.input.enablesReturnKeyAutomatically = FALSE;
self->demo_lines = NULL;
self.input.text = @"";
}
- (IBAction)okPressed:(id)sender {
[self enterPressed];
[self enterPressed];
}
- (IBAction)demo:(id)sender {
if (self->demo_lines) { // demo already running
[self enterPressed];
} else {
[self loadDemo];
}
if (self->demo_lines) { // demo already running
[self enterPressed];
} else {
[self loadDemo];
}
}
- (IBAction)clear:(id)sender {
[self unloadDemo];
NSString *string = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:@"tape" ofType:@"html"] encoding:NSUTF8StringEncoding error:NULL];
[self.tape loadHTMLString:string baseURL:NULL];
[self unloadDemo];
NSString *string = [NSString
stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tape" ofType:@"html"]
encoding:NSUTF8StringEncoding
error:NULL];
[self.tape loadHTMLString:string baseURL:NULL];
}
@end

View File

@ -16,6 +16,7 @@
- (instancetype)initWithFrame:(CGRect)frame;
- (void)suggestFor:(NSString *)text;
@property (weak) id<SuggestionDelegate> delegate;
@property(weak) id<SuggestionDelegate> delegate;
@end

View File

@ -7,192 +7,158 @@
#define maxSuggestions 4 + 3
@implementation Suggestion {
NSString *text;
NSRange range;
NSString *text;
NSRange range;
NSMutableOrderedSet *options;
NSMutableArray *buttons;
NSArray *possibleSuggestions;
NSCharacterSet *breakingChars;
NSMutableOrderedSet *options;
NSMutableArray *buttons;
NSArray *possibleSuggestions;
NSCharacterSet *breakingChars;
}
- (instancetype)init
{
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
self = [self initWithFrame:CGRectMake(0.0f, 0.0f, screenWidth, 36.0f)];
return self;
- (instancetype)init {
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
self = [self initWithFrame:CGRectMake(0.0f, 0.0f, screenWidth, 36.0f)];
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame inputViewStyle:UIInputViewStyleKeyboard];
if (self) {
possibleSuggestions = @[
@")base ",
@")debug ",
@")format ",
@")maxdigits ",
@")op ",
@")origin ",
@")prec ",
@")prompt ",
@")seed ",
@"cos ",
@"iota ",
@"log ",
@"max ",
@"min ",
@"pi ",
@"rho ",
@"sin ",
@"sqrt ",
@"tan "
];
breakingChars =
[NSCharacterSet characterSetWithCharactersInString:@"/+-*,^|= "];
options = [[NSMutableOrderedSet alloc] initWithCapacity:maxSuggestions];
buttons = [[NSMutableArray alloc] init];
self.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.05f];
[self setSuggestions:nil];
}
return self;
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame inputViewStyle:UIInputViewStyleKeyboard];
if (self) {
possibleSuggestions = @[
@")base ", @")debug ", @")format ", @")maxdigits ", @")op ", @")origin ", @")prec ",
@")prompt ", @")seed ", @"cos ", @"iota ", @"log ", @"max ", @"min ", @"pi ", @"rho ",
@"sin ", @"sqrt ", @"tan "
];
breakingChars = [NSCharacterSet characterSetWithCharactersInString:@"/+-*,^|= "];
options = [[NSMutableOrderedSet alloc] initWithCapacity:maxSuggestions];
buttons = [[NSMutableArray alloc] init];
self.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.05f];
[self setSuggestions:nil];
}
return self;
}
- (void)suggestFor:(NSString *)t
{
text = t;
range =
[text rangeOfCharacterFromSet:breakingChars options:NSBackwardsSearch];
if (range.location == NSNotFound) {
range.location = 0;
range.length = text.length;
- (void)suggestFor:(NSString *)t {
text = t;
range = [text rangeOfCharacterFromSet:breakingChars options:NSBackwardsSearch];
if (range.location == NSNotFound) {
range.location = 0;
range.length = text.length;
} else {
if (range.location > 0 && [text characterAtIndex:range.location - 1] == ')') {
// Special case for suggestions that start with ") ".
range.location -= 1;
range.length++;
} else {
if (range.location > 0 &&
[text characterAtIndex:range.location - 1] == ')') {
// Special case for suggestions that start with ") ".
range.location -= 1;
range.length++;
} else {
range.location += 1;
range.length -= 0;
}
range.location += 1;
range.length -= 0;
}
range.length = text.length - range.location;
if (range.length == 0) {
[self setSuggestions:nil];
} else {
NSString *prefix = [text substringWithRange:range];
// TODO: make not so slow.
NSArray *suggestions = @[];
for (NSString *suggestion in possibleSuggestions) {
if ([suggestion hasPrefix:prefix] && prefix.length < suggestion.length) {
suggestions = [suggestions arrayByAddingObject:suggestion];
}
}
if (suggestions.count > 3) {
suggestions = nil;
}
[self setSuggestions:suggestions];
}
range.length = text.length - range.location;
if (range.length == 0) {
[self setSuggestions:nil];
} else {
NSString *prefix = [text substringWithRange:range];
// TODO: make not so slow.
NSArray *suggestions = @[];
for (NSString *suggestion in possibleSuggestions) {
if ([suggestion hasPrefix:prefix] && prefix.length < suggestion.length) {
suggestions = [suggestions arrayByAddingObject:suggestion];
}
}
[self setNeedsLayout];
if (suggestions.count > 3) {
suggestions = nil;
}
[self setSuggestions:suggestions];
}
[self setNeedsLayout];
}
- (void)setSuggestions:(NSArray *)suggestions
{
[options removeAllObjects];
- (void)setSuggestions:(NSArray *)suggestions {
[options removeAllObjects];
if ([suggestions respondsToSelector:
@selector(countByEnumeratingWithState:objects:count:)]) {
for (NSString *suggestion in suggestions) {
if (options.count < maxSuggestions) {
[options addObject:suggestion];
} else {
break;
}
}
if ([suggestions respondsToSelector:@selector(countByEnumeratingWithState:objects:count:)]) {
for (NSString *suggestion in suggestions) {
if (options.count < maxSuggestions) {
[options addObject:suggestion];
} else {
break;
}
}
}
}
- (void)layoutSubview:(NSString *)t at:(CGFloat)x width:(CGFloat)w
{
UIButton *b = [[UIButton alloc]
initWithFrame:CGRectMake(x, 0.0f, w, self.bounds.size.height)];
[b setTitle:t forState:UIControlStateNormal];
b.titleLabel.adjustsFontSizeToFitWidth = YES;
b.titleLabel.textAlignment = NSTextAlignmentCenter;
[b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[b addTarget:self
action:@selector(buttonTouched:)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:b];
- (void)layoutSubview:(NSString *)t at:(CGFloat)x width:(CGFloat)w {
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(x, 0.0f, w, self.bounds.size.height)];
[b setTitle:t forState:UIControlStateNormal];
b.titleLabel.adjustsFontSizeToFitWidth = YES;
b.titleLabel.textAlignment = NSTextAlignmentCenter;
[b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[b addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:b];
if (x > 0) {
UIView *line = [[UIView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 0.5f, self.bounds.size.height)];
line.backgroundColor =
[UIColor colorWithRed:0.984 green:0.977 blue:0.81 alpha:1.0];
[b addSubview:line];
}
if (x > 0) {
UIView *line =
[[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.5f, self.bounds.size.height)];
line.backgroundColor = [UIColor colorWithRed:0.984 green:0.977 blue:0.81 alpha:1.0];
[b addSubview:line];
}
[buttons addObject:b];
[buttons addObject:b];
}
- (void)layoutSubviews
{
for (UIView *subview in buttons) {
[subview removeFromSuperview];
}
[buttons removeAllObjects];
- (void)layoutSubviews {
for (UIView *subview in buttons) {
[subview removeFromSuperview];
}
[buttons removeAllObjects];
CGFloat symbolWidth = 40.0f;
[self layoutSubview:@"+" at:0 * symbolWidth width:symbolWidth];
[self layoutSubview:@"-" at:1 * symbolWidth width:symbolWidth];
[self layoutSubview:@"*" at:2 * symbolWidth width:symbolWidth];
[self layoutSubview:@"/" at:3 * symbolWidth width:symbolWidth];
CGFloat symbolWidth = 40.0f;
[self layoutSubview:@"+" at:0 * symbolWidth width:symbolWidth];
[self layoutSubview:@"-" at:1 * symbolWidth width:symbolWidth];
[self layoutSubview:@"*" at:2 * symbolWidth width:symbolWidth];
[self layoutSubview:@"/" at:3 * symbolWidth width:symbolWidth];
for (int i = 0; i < options.count; i++) {
NSString *suggestion = options[i];
CGFloat width =
(self.bounds.size.width - (4 * symbolWidth)) / options.count;
CGFloat x = (4 * symbolWidth) + (i * width);
[self layoutSubview:suggestion at:x width:width];
}
for (int i = 0; i < options.count; i++) {
NSString *suggestion = options[i];
CGFloat width = (self.bounds.size.width - (4 * symbolWidth)) / options.count;
CGFloat x = (4 * symbolWidth) + (i * width);
[self layoutSubview:suggestion at:x width:width];
}
}
- (void)buttonTouched:(UIButton *)button
{
NSTimeInterval duration = 0.08f;
[UIView
animateWithDuration:duration
animations:^{
[button setBackgroundColor:[UIColor whiteColor]];
- (void)buttonTouched:(UIButton *)button {
NSTimeInterval duration = 0.08f;
[UIView animateWithDuration:duration
animations:^{
[button setBackgroundColor:[UIColor whiteColor]];
if ([self.delegate
respondsToSelector:@selector(suggestionReplace:)]) {
NSString *t = self->text;
if (t == nil) {
t = @"";
}
if (button.currentTitle.length == 1) {
// Special case for +, -, *, /.
t = [t stringByAppendingString:button.currentTitle];
} else {
t = [self->text stringByReplacingCharactersInRange:
self->range withString:button.currentTitle];
}
[self performSelector:@selector(suggestionReplace:)
withObject:t
afterDelay:duration * 0.8f];
}
[button performSelector:@selector(setBackgroundColor:)
withObject:[UIColor clearColor]
afterDelay:duration];
}];
if ([self.delegate respondsToSelector:@selector(suggestionReplace:)]) {
NSString *t = self->text;
if (t == nil) {
t = @"";
}
if (button.currentTitle.length == 1) {
// Special case for +, -, *, /.
t = [t stringByAppendingString:button.currentTitle];
} else {
t = [self->text stringByReplacingCharactersInRange:self->range
withString:button.currentTitle];
}
[self performSelector:@selector(suggestionReplace:)
withObject:t
afterDelay:duration * 0.8f];
}
[button performSelector:@selector(setBackgroundColor:)
withObject:[UIColor clearColor]
afterDelay:duration];
}];
}
- (void)suggestionReplace:(NSString *)t
{
[self.delegate performSelector:@selector(suggestionReplace:) withObject:t];
- (void)suggestionReplace:(NSString *)t {
[self.delegate performSelector:@selector(suggestionReplace:) withObject:t];
}
@end