2015年4月20日 星期一

Create a UIColor from a hex string

UI 設計師給的 design guideline 都給 hex string 色碼,



如果是要寫 code 去控制, 比較好的解法, 我想是用這個別人寫好的 class 來用.
https://github.com/mRs-/HexColors

Example iOS

// with hash
UIColor *colorWithHex = [UIColor colorWithHexString:@"#ff8942" alpha:1];

// without hash
UIColor *secondColorWithHex = [UIColor colorWithHexString:@"ff8942" alpha:1];

// short handling
UIColor *shortColorWithHex = [UIColor colorWithHexString:@"fff" alpha:1];



相關文章:





2015年3月23日 星期一

How to deselect a selected row when selecting the new row in a tableview

想設計一個類似 Radio 多選一的 table row 效果, 當選擇某一筆時, 其他被選擇的會取消選取.

範例:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  for (int i = 0; i < [tableView numberOfRowsInSection:0]; i++) {
      [tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
  } 
   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell_check.png"]];   

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

     cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"white_cell.png"]]; 

}

這個寫法, 似乎可行, 但還有問題, 當資料筆數多時, 要記得處理 cell 重覆使用時, 初始化預設值的部份.

在 TableView的屬性裡設定 "Selection" 值為 "Multiple Section".

當某一例不希望被 deselect 時, 要加入回 selected status, 請使用 selectRowAtIndexPath:
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [[self tableView] reloadData];

    int isPage = [_delegate returnPageNumber];

    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:(isPage) inSection:0];
    NSLog(@"viewDidAppear scrollIndexPath is %@",scrollIndexPath);

    [[self tableView] selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

2015年3月18日 星期三

學習 UICollectionView

我在承接了前人的code,  在要加入新功能時發現有趣的東西, 一開始以為是使用 TableView , 看了 code 發現是 collection view, 使用起來和 tableview & table cell 差不多, 但功能比較少.


相關文章:


2015年3月16日 星期一

[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread

遇到這個 Error, 在使用 Notification 傳遞事件時. 解法就是把 keyboard 或 alert 相關 UI 的 code, 要放回去 main thread 裡執行.

Swift example:
The main issue is that your error message is reporting that "... may only be called from the main thread". So you presumably have invoked this code from within a background thread (perhaps a completion block for network request or something like that). So you have to dispatch this code back to the main queue:
dispatch_async(dispatch_get_main_queue()) {
    let vc = self.storyboard.instantiateViewControllerWithIdentifier(viewID) as UIViewController
    showViewController(vc, sender: self)
}

obj-c example:
dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:...
    [alertView show];
});


2015年3月12日 星期四

Send and receive messages through NSNotificationCenter in Objective-C

用 delegate 覺得太麻煩, 偷懶的我使用 notification 在不同的 view 之間傳資料.


==============================================

Kira 的教學:

http://www.idev101.com/code/Cocoa/Notifications.html


==============================================
Posting Notifications
[[NSNotificationCenter defaultCenter] postNotificationName:@"reachabilityChanged" object:self];

==============================================
Listening for Notifications
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(handleReachabilityChange:)        
                                             name:@"reachabilityChanged" 
                                           object:nil];
==============================================
- (void)handleReachabilityChange:(NSNotification *)note {
    NSDictionary *theData = [note userInfo];
    if (theData != nil) {
        NSNumber *n = [theData objectForKey:@"isReachable"];
        BOOL isReachable = [n boolValue];
        NSLog(@"reachable: %d", isReachable);
    }
}
==============================================
-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}



Stack OverFlow 上的 sample:
http://stackoverflow.com/questions/2191594/send-and-receive-messages-through-nsnotificationcenter-in-objective-c

@implementation TestClass

- (void) dealloc
{
    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (id) init
{
    self = [super init];
    if (!self) return nil;

    // Add this instance of TestClass as an observer of the TestNotification.
    // We tell the notification center to inform us of "TestNotification"
    // notifications using the receiveTestNotification: selector. By
    // specifying object:nil, we tell the notification center that we are not
    // interested in who posted the notification. If you provided an actual
    // object rather than nil, the notification center will only notify you
    // when the notification was posted by that particular object.

    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveTestNotification:) 
        name:@"TestNotification"
        object:nil];

    return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
    // [notification name] should always be @"TestNotification"
    // unless you use this method for observation of other notifications
    // as well.

    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

@end
... somewhere else in another class ...
- (void) someMethod
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

}


2015年3月11日 星期三

Proper way to convert BOOL value into String

Error example:
NSNumber *num = 0;
    BOOL myBool = [num boolValue];
    NSLog(@"bool is: %@",myBool);

boolean to string example:
NSLog(@"bool is: %@", (myBool) ? @"YES" : @"NO");

boolean to int example:
int myInt = (myBool ? 1 : 0);


Format specifiers supported by the NSString formatting methods and CFString formatting functions
Specifier
Description
%@
Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
%%
'%' character.
%d%D
Signed 32-bit integer (int).
%u%U
Unsigned 32-bit integer (unsigned int).
%x
Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f.
%X
Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F.
%o%O
Unsigned 32-bit integer (unsigned int), printed in octal.
%f
64-bit floating-point number (double).
%e
64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent.
%E
64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent.
%g
64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
%G
64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise.
%c
8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit.
%C
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit.
%s
Null-terminated array of 8-bit unsigned characters. Because the %s specifier causes the characters to be interpreted in the system default encoding, the results can be variable, especially with right-to-left languages. For example, with RTL, %s inserts direction markers when the characters are not strongly directional. For this reason, it’s best to avoid %s and specify encodings explicitly.
%S
Null-terminated array of 16-bit Unicode characters.
%p
Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x.
%a
64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent.
%A
64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent.
%F
64-bit floating-point number (double), printed in decimal notation.

2015年2月26日 星期四

UIView set autocorrectionType attribute

在維護前人的前人所留下來的 iOS code, 有一段是要對 keyboard 做設定, 由於之前完全沒 implement 過類似的, google 了一下, 查出來的 code 連回 apple 官網去看, 也看不出個所以然, 手動 try error 一直 crash. 今天終於找到一個 sample code, 照著打, 就過了, keyboard 的 property 就可以 access 了, 從這份 code 我們可以看的出來, 似乎沒有人這樣子寫了, 所以我 copy from 的這個 qt plugin的 sample 是把 property 拿掉. @_@; 直接使用 UIView.

copy from: qioswindow.h
https://qt.gitorious.org/qt/qtbase/source/68762151dbf45fbb44e140ac2ad13dbe8d357352:src/plugins/platforms/ios/qioswindow.h
======================================
diff --git a/src/plugins/platforms/ios/qioswindow.h b/src/plugins/platforms/ios/qioswindow.h
index cb2854d..d0df791 100644
--- a/src/plugins/platforms/ios/qioswindow.h
+++ b/src/plugins/platforms/ios/qioswindow.h
@@ -49,31 +49,6 @@
 class QIOSContext;
 class QIOSWindow;
 
-@interface EAGLView : UIView <UIKeyInput>
-{
-    UITextAutocapitalizationType autocapitalizationType;
-    UITextAutocorrectionType autocorrectionType;
-    BOOL enablesReturnKeyAutomatically;
-    UIKeyboardAppearance keyboardAppearance;
-    UIKeyboardType keyboardType;
-    UIReturnKeyType returnKeyType;
-    BOOL secureTextEntry;
-    QIOSWindow *m_qioswindow;
-}
-
-- (id)initWithQIOSWindow:(QIOSWindow *)qioswindow;
-- (void)sendMouseEventForTouches:(NSSet *)touches withEvent:(UIEvent *)event fakeButtons:(Qt::MouseButtons)buttons;
-
-@property(nonatomic) UITextAutocapitalizationType autocapitalizationType;
-@property(nonatomic) UITextAutocorrectionType autocorrectionType;
-@property(nonatomic) BOOL enablesReturnKeyAutomatically;
-@property(nonatomic) UIKeyboardAppearance keyboardAppearance;
-@property(nonatomic) UIKeyboardType keyboardType;
-@property(nonatomic) UIReturnKeyType returnKeyType;
-@property(nonatomic, getter=isSecureTextEntry) BOOL secureTextEntry;
-
-@end

======================
另外, 就是直接使用 UITEXTVIEW 的時候, 要先 set 好 property 再去 show keyboard, 才會套用到想要的UI, 不然會吃到 apple 的 default value, 那可能不會是你預期的結果.

[How To] Disable UITextField Predictive Text.
Answer:
myTextField.autocorrectionType = UITextAutocorrectionTypeNo; has to be placed before [myTextField becomeFirstResponder]; to be effective.


======================

相關文章:

TextField 輸入結束後的收起小鍵盤
http://ios-imaxlive.blogspot.tw/2013/07/textfield-resignfirstresponder.html

Facebook 留言