建立一個 UIImageView
要以程式設計方式建立 UIImageView
,你需要做的就是建立 UIImageView
的例項:
//Swift
let imageView = UIImageView()
//Objective-C
UIImageView *imageView = [[UIImageView alloc] init];
你可以使用 CGRect
設定 UIImageView
的大小和位置:
//Swift
imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
//Objective-C
imageView.frame = CGRectMake(0,0,200,200);
或者你可以在初始化期間設定大小:
//Swift
UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
//Objective-C
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,200,200);
//Alternative way of defining frame for UIImageView
UIImageView *imageView = [[UIImageView alloc] init];
CGRect imageViewFrame = imageView.frame;
imageViewFrame.size.width = 200;
imageViewFrame.size.height = 200;
imageViewFrame.origin.x = 0;
imageViewFrame.origin.y = 0;
imageView.frame = imageViewFrame;
注意:你必須匯入
UIKit
才能使用UIImageView
。