2016年1月18日 星期一

iOS tips - dismiss keyboard

textfield是我們常常會使用到的元件,而有時在原本的VC不需要寫textfield的delegate時要收起鍵盤常常是一件麻煩的事情,加上下面這段code就可以在鍵盤外的畫面touch然後收下鍵盤

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];
然而如果是在tableview加上這段code的話會發現除了textfield以外,原本的cell都不能點擊了,此時再將我們宣告的gestureRecognizer設定一個屬性
gestureRecognizer.cancelsTouchesInView = NO
如此一來tableview的cell也可以正常運作了!

2016年1月9日 星期六

iOS tips - Local Notification

我們常常在內部某一個VC完成一個A task後,需要讓另一個VC能夠根據A task的結果或內容去做另一個B task,此時就需要在A task內加上通知,B task的VC加上一個observer,如此一來只要A task完成後發出notification,B task的觀察者馬上能夠知道A task已完成,然後去執行他該做的工作,可參考以下代碼

// Add an observer that will respond to loginComplete [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bTask:) name:@"aTaskComplete" object:nil]; // Post a notification to loginComplete [[NSNotificationCenter defaultCenter] postNotificationName:@"aTaskComplete" object:nil]; // the function specified in the same class where we defined the addObserver - (void) bTask:(NSNotification *)note { NSLog(@"Received Notification - Do something here!"); }

2016年1月6日 星期三

iOS tips - UIRefreshControl

幾乎每個有tableview的app都會用到UIRefreshControl,也就是下拉更新(pull down to refresh),當所使用的view controller是基本的tableview的話,實現的方法相當簡單,在viewDidload中加上這些code來initial一個UIRefreshControl
- (void)viewDidLoad {
    [super viewDidLoad];
    refreshControl = [[UIRefreshControl alloc]init];
    [self.mytableView addSubview:refreshControl];
    [refreshControl addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
}
然後在相對應的selector上加上個人更新table的method,很簡單的就完成了一個下拉更新的功能
- (void)refreshTable {
    //TODO: refresh your data
    [refreshControl endRefreshing];
    [self.mytableView reloadData];
}

iOS tips - 動態設置label width

在設置一個UILabel時,常常會遇到設置的frame width不夠文字內容使用的問題,雖說也有adjustsFontSizeToFitWidth這個property可以設定,但是調整label字型大小通常不會是設計的選項之一.
此時我們可以先依靠"sizeWithFont"這個function來detect要帶入的文字的寬度,再去設置UILabel的frame
//use this for system font 
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;

label.frame = CGRectMake(point.x, point.y, width,height);
如此就能夠根據文字內容來動態定義Label的width了