我需要在SegmentController - Swift中设置一个图像。
const strings = [
'https://open.spotify.com/user/spotify/playlist/37i9dQZF1DZ06evO2ZpGiQ?si=-6S0EBlURrao__YyIOW6bg',
'spotify:user:spotify:playlist:37i9dQZF1DZ06evO2ZpGiQ'
];
let regex = /^(?:https:\/\/open\.spotify\.com|spotify)([\/:])user\1([^\/]+)\1playlist\1([a-z0-9]+)/gi;
strings.forEach((str) => {
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log("user id: " + m[2]);
console.log("playlist id: " + m[3]);
}
});
如何在分段控制器内正确修复图像。
我试过了:
let testTypeSegmentedControl: UISegmentedControl = {
let types = [“Green”, “Blue”] // v_concreteSelectedIndex
let sc = UISegmentedControl(items: types)
sc.setImage((UIImage(named: "Green_Main.png")), forSegmentAt: 0)
sc.selectedSegmentIndex = 0
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = .black
return sc
}()
但似乎没有成功。
我尝试使用约束,但我不知道该怎么做。
有任何建议如何进行?
答案 0 :(得分:1)
结果不是您所期望的,因为您使用的原始.png图像的分辨率更高。你永远不应该使用"大"图像只显示一个小图片。完整的图像将被加载到内存中,并且只会显示10%的像素,因此您将无需使用大量内存。
如果您真的想要使用此资源,可以执行的操作是使用之前的代码创建新图像,并使用此新生成的图像。
以下方法会返回您可以在UISegmentedControl
中使用的新图像,并且可以释放大图像。
func image(with image: UIImage?, scaledTo newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(newSize)
image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
在您的代码中:
let testTypeSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["One", "Two"])
sc.selectedSegmentIndex = 0
sc.translatesAutoresizingMaskIntoConstraints = false
return sc
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(testTypeSegmentedControl)
let newImage = image(with: (UIImage(named: "watermelon.png")), scaledTo: CGSize(width: 32, height: 30))
testTypeSegmentedControl.setImage(newImage , forSegmentAt: 0)
}