如何在代码中设置UIButton的图像?
我有这个:
UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTwo];
但不知道什么会为它设置图像。
Swift 3版本(butt_img必须是Image Set into Assets。xcassets或图像。xcassets文件夹在Xcode):
btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)
无论如何,如果你想让图像缩放到按钮的大小,你可以在它上面添加一个UIImageView,并给它分配你的图像:
let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)