创建一个 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
。