问题描述
我想用slider slizer来改变uiview图片的大小。使用 Nslayout 约束,它会创建一个固定对象,因此我将约束添加为变量。所以我假设在增加功能中 startCon 将被停用,而 changeCon 将被激活。我有一段时间没有将约束用作 var 并且不知道该怎么做。但我想使用 nslayout 约束定位图片,然后使用滑块一起更改宽度和高度。
import UIKit
class ViewController: UIViewController{
var pic = UIView();var slizer = UiSlider()
var startCon: NSLayoutConstraint!
var changeCon: NSLayoutConstraint!
override func viewDidLoad() {
[pic,slizer].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
NSLayoutConstraint.activate([
pic.centerYAnchor.constraint(equalTo: view.centerYAnchor),pic.centerXAnchor.constraint(equalTo: view.centerXAnchor),pic.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.3),pic.widthAnchor.constraint(equalTo: view.widthAnchor,slizer.bottomAnchor.constraint(equalTo: view.bottomAnchor),slizer.leadingAnchor.constraint(equalTo: view.leadingAnchor),slizer.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.2),slizer.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 1),])
pic.backgroundColor = .orange
slizer.addTarget(self,action: #selector(increase),for: .touchDown)
}
@objc func increase(){
//increase decrease size of pic
}
}
解决方法
您可以保存负责图像大小的属性,在滑块操作中更改这些值。例如:
在方法 pic.heightAnchor.constraint
操作中更改值 increase
的乘数。
无法修改激活的约束。你必须禁用你的限制并设置一个新的。
var pic = UIView()
var slizer = UISlider()
var slidermultiplier: CGFloat = 0.3
var widthConstraints: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
widthConstraints = pic.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: slidermultiplier)
[pic,slizer].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
NSLayoutConstraint.activate([
pic.centerYAnchor.constraint(equalTo: view.centerYAnchor),pic.centerXAnchor.constraint(equalTo: view.centerXAnchor),pic.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.3),widthConstraints!,slizer.bottomAnchor.constraint(equalTo: view.bottomAnchor),slizer.leadingAnchor.constraint(equalTo: view.leadingAnchor),slizer.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.2),slizer.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 1),])
pic.backgroundColor = .orange
// changed to .valueChanged
slizer.addTarget(self,action: #selector(increase),for: .valueChanged)
}
@objc func increase() {
slidermultiplier = CGFloat(slizer.value)
widthConstraints?.isActive = false
widthConstraints = pic.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: slidermultiplier)
widthConstraints?.isActive = true
}
你可以对高度做同样的事情。
您还可以为您的 UISlider
设置最小值和最大值,以获得 Range
的乘数。