網頁

顯示具有 UIView 標籤的文章。 顯示所有文章
顯示具有 UIView 標籤的文章。 顯示所有文章

2012年6月18日 星期一

視圖控制資源

【環境:xCode4.3.2 , ios5.1 , USE ARC】
說明:
  1. viewWillAppear
  2. viewDidAppear
  3. viewWillDisappear
  4. viewDidDisappear
這四個方法其實是視圖提供的一些狀態更新資訊,當畫面有異動時,他會藉由這四個方法來通知我們,不過不見得所有的程式都需要知道這些更新的狀態。
所以viewWillAppear和viewDidAppear都是適合修改標題的時機。

除了這四種還有
  • viewDidLoad:當試圖完成載入時呼叫,大部份的情況只會被呼叫依次,通常需要額外載入資料都會在這個方法中實作。在前面介紹修改標題的動作移到此處也是相當合適的一個地方。
  • viewDidUnload:當視圖卸載之後呼叫。

視圖除了上述幾種,還包含
-(void) awakeFromNib

當視圖是由xib載入而不是由手動載入時,系統會跳過試圖內建的初始化方式
-(id) initWithFrame:(CGRect)frame;

改由呼叫另一個初始化方法
-(id) initWithCoder:(NSCoder *)decoder
接下來就會呼叫awakeFromNib,因此當我門想要額外對視圖作設定,而這個視圖又剛好是自動由xib檔案載入,awakeFromNib就是一個很適合為視圖進行額外設定的地方。


As always , if you have any question , feel free to contact me.
有任何問題,請聯絡我

歡迎轉載,請註明出處,感謝。

2012年6月5日 星期二

UIView

【環境:xCode4.2 , ios5.0】

基本UIView,這次主要在於view的移動,還有初階的使用,利用按鈕移動uiview和切換uiview
應用了兩種不同的方法
下一篇會完整介紹UIView的完整功能
比較值得探討的就是
UIViewImage *a1;
a1.frame.size.width & a1.frame.origin.x
一個是自己本身的寬度,另一個是自己本身在父框的初始位置

程式碼下載

截圖:




2012年6月4日 星期一

AVFoundation應用、Google_TTS

【環境:xCode4.3.2 , ios5.1】

說明:
以uitabBarController為基礎框架,自定義tabBar,我的tabBarItem用的是30x30的大小,且背景須為透明,顏色為淺色系。
使用uitextview、AVFoundation應用、Google_TTS。
其中tts的部份加入,中英文判斷。
應用到了一點QuartzCore去處理uitextview的外框。

值得注意的還有tts若想用其他語言發音
http://translate.google.com/translate_tts?tl=en&q=text
則更改紅字的部份,此部份為countryCode

故此範例須引用
#import <AVFoundation/AVFoundation.h> 
#import <QuartzCore/QuartzCore.h>
引用的protocol有以下兩個
<UITabBarDelegate,UITabBarControllerDelegate>
<UITextViewDelegate>

※若你的音效程式碼運行正確,但實機測試卻撥不出來,可以檢查<你iphone的震動的按鈕是否打開>。

※若simulation也無聲音,大概就必須檢查你的程式碼stop & pause部分代碼,是否和play搞混。


範例下載  若只需單純的tts 參考,此部份提供當初我網路上參考tts的程式






<以下部分程式碼範例-主要為textview應用和google tts的應用>
 
//
//  view2.m
//  sound & tts
//
//  Created by jhaoheng on 2012/6/1.
//  Copyright (c) 2012年 __n11_studio__. All rights reserved.
//

#import "view2.h"

//由於本範例有使用到 Layer 類別的方法,所以必須先匯入其對應的標頭檔和 Framework。
#import <QuartzCore/QuartzCore.h>

@implementation view2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.title = @"three";
        UIImage *img_speak = [UIImage imageNamed:@"google.png"];
        UITabBarItem *item3 = [[UITabBarItem alloc]initWithTitle:@"G_TTS" image:img_speak tag:1]; 
        self.tabBarItem = item3;
        
        /*
        The item’s image. If nil, an image is not displayed.
        
        The images displayed on the tab bar are derived from this image. If this image is too large to fit on the tab bar, it is scaled to fit. The size of an tab bar image is typically 30 x 30 points. The alpha values in the source image are used to create the unselected and selected images—opaque values are ignored.
        */
        /*
         if you want to create icons for iPhone UITabBar ,you can read this website
         http://steveweller.com/articles/toolbar-icons/
        */
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    input_text = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
    input_text.font = [UIFont fontWithName:@"Arial" size:20];
    input_text.textColor = [UIColor whiteColor];
    input_text.delegate = self;
    input_text.backgroundColor = [UIColor whiteColor];
    input_text.text = @"you can type something in this frame and click the speaker button to pronounce";
    input_text.returnKeyType = UIReturnKeyDefault;
    input_text.keyboardType = UIKeyboardTypeDefault;
    /*
     autocapitalizationType — 首字大寫
     autocorrectionType — 自動更正錯字
     enablesReturnKeyAutomatically — 確認使用者有輸入文字後才啟用return鍵
     keyboardAppearance — 鍵盤外型
     keyboardType — 鍵盤種類
     returnKeyType — return鍵的類型
     secureTextEntry — 隱藏輸入的文字
    */
    //設定是否可捲動
    input_text.scrollEnabled = YES;
    //自適應高度
    //text.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    
    //設定橘色背景與棕色邊框
    [input_text setBackgroundColor:[UIColor orangeColor]];
    [[input_text layer] setBorderColor:[[UIColor brownColor] CGColor]];
    //邊框粗細
    [[input_text layer] setBorderWidth:1.5];
    //設定圓角程度
    [[input_text layer] setCornerRadius:20];
    /*指定內文字體大小並置中
    [text setFont:[UIFont boldSystemFontOfSize:50.0]];
    [text setTextAlignment:UITextAlignmentCenter];
    */
    //設定無法再被編輯
    [input_text setEditable:YES];
     
    //使內文保持在UITextView邊框之內
    [input_text setClipsToBounds: YES];
    [self.view addSubview:input_text];
    
    UIButton *speaker = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [speaker setTitle:@"speaker" forState:UIControlStateNormal];
    [speaker setTitle:@"connect" forState:UIControlStateHighlighted];
    speaker.frame = CGRectMake(20, 295, 280, 40);
    [speaker addTarget:self action:@selector(machine_speak) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:speaker];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -uibutton
-(void)machine_speak
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.mp3"];
    NSString *urlString;
    if ([input_text.text canBeConvertedToEncoding: NSASCIIStringEncoding]) {//如果是英語
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=en&q=%@",input_text.text];
    }  
    else { //如果是非英語 
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=zh-TW&q=%@",input_text.text];
    } 
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" forHTTPHeaderField:@"User-Agent"];
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    [data writeToFile:path atomically:YES];
    
    NSError *err;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
    {    
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&err];
        player.volume = 0.8f;
        [player prepareToPlay];
        [player setNumberOfLoops:0];
        [player play];    
    }
     
}

#pragma mark - UITextView Delegate Methods     

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)closetext
{    
    if ([closetext isEqualToString:@"\n"]) {    
        
        [input_text resignFirstResponder];    
        
        return NO;    
        
    }
    return YES;    
}

@end
 

2012年5月31日 星期四

網路檢測

20120613新增apple官網範例(使用方式略有差異)

【環境:xCode4.2 , ios5.1】
宣告:利用 UIDevice 的功能
說明:
Connectivity(.h .m)資料來源參考-掌握iPhone SDK 程式開發技巧
利用該原碼提供網路偵測的判斷,使用前須先挂載 SystemConfiguration.framework,挂載方式請參閱
引用方式[UIDevice cellularConnected][UIDevice wiFiConnected][UIDevice networkConnected]即可使用

功能執行:
1.利用淡入淡出視覺頁面


2.切換進入功能頁,點選按鈕可偵測網路....啓動語音或者視訊等相關功能



範例下載

<以下範例>
Connectivity.h
 
#import <SystemConfiguration/SCNetworkReachability.h>

//add SystemConfiguration Framework

@interface UIDevice (DeviceConnectivity)

+(BOOL)cellularConnected; 
+(BOOL)wiFiConnected;
+(BOOL)networkConnected;   

@end
Connectivity.m
#import "Connectivity.h"

#define EXTERNAL_HOST @"google.com"

@implementation UIDevice (DeviceConnectivity)

+(BOOL)cellularConnected{// EDGE or GPRS
  SCNetworkReachabilityFlags    flags = 0;
  SCNetworkReachabilityRef      netReachability = NULL;  
  netReachability     = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [EXTERNAL_HOST UTF8String]);
  if(netReachability){
    SCNetworkReachabilityGetFlags(netReachability, &flags);
    CFRelease(netReachability);
  }
  if(flags & kSCNetworkReachabilityFlagsIsWWAN){
    return YES;
  }
  return NO;
}
+(BOOL)wiFiConnected{
  if([self cellularConnected]){
    return NO;
  }
  return [self networkConnected];
}
+(BOOL)networkConnected{
  SCNetworkReachabilityFlags     flags = 0;
  SCNetworkReachabilityRef       netReachability = NULL;
  BOOL                           retrievedFlags = NO;
  
  netReachability     = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [EXTERNAL_HOST UTF8String]);
  if(netReachability){
    retrievedFlags      = SCNetworkReachabilityGetFlags(netReachability, &flags);
    CFRelease(netReachability);
  }
  if (!retrievedFlags || !flags){
    return NO;
  }
  return YES;
}
@end