本文整理 iOS 開發中常見的基礎操作,方便隨時查閱。
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 100, 100);
[btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:@"確定" forState:UIControlStateNormal];
[self.view addSubview:btn];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 44)];
lbl.text = @"test";
lbl.textColor = [UIColor purpleColor];
lbl.font = [UIFont systemFontOfSize:18];
lbl.backgroundColor = [UIColor clearColor];
[self.view addSubview:lbl];
需引入 QuartzCore:
#import <QuartzCore/QuartzCore.h>
aView.layer.cornerRadius = 10;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
[self.view addGestureRecognizer:tap];
需遵從 UITextFieldDelegate 協議,設定 placeholder、borderStyle、delegate 等屬性,並在 textFieldShouldReturn: 中呼叫 resignFirstResponder 收起鍵盤。
設定邊框寬度與顏色:
text.layer.borderWidth = 1;
text.layer.borderColor = [UIColor redColor].CGColor;
CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:CGSizeMake(320, 1000) lineBreakMode:NSLineBreakByWordWrapping];
需加入 AVFoundation.framework,透過 AVAudioPlayer 建立播放器,呼叫 prepareToPlay 與 play 即可播放。
需加入 QuartzCore.framework,建立 UIActivityIndicatorView,設定樣式、frame 後加入視圖,再呼叫 startAnimating 開始動畫。
以上是 iOS 開發中常見的基礎元件操作速查,適合初學者反覆練習。