使用滑块控制 nslayoutConstraint 的宽度和高度
Posted
技术标签:
【中文标题】使用滑块控制 nslayoutConstraint 的宽度和高度【英文标题】:Use slider to control width and height of a nslayoutConstraint 【发布时间】:2019-12-07 03:38:15 【问题描述】:我的代码在 swift 中,我想使用滑块 (sd) 来控制 imageview pic 的宽度和高度。我在下面尝试的方法不起作用。只要我移动滑块 sd 和 pic disaper。当滑块移动图片时,应该逐渐改变它的宽度和高度。我在调试区域看到了百分比变化,但它在图片上不起作用。我的代码不使用情节提要。
import UIKit
class ViewController: UIViewController
var sd = UISlider()
var pic = UIImageView()
var start = [NSLayoutConstraint]()
var change = [NSLayoutConstraint]()
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
[sd,pic].forEach
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
start = [
pic.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
pic.topAnchor.constraint(equalTo: view.centerYAnchor, constant : -225),
pic.widthAnchor.constraint(equalToConstant: 300),
pic.heightAnchor.constraint(equalToConstant: 450),
sd.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
sd.topAnchor.constraint(equalTo: view.centerYAnchor, constant : +250),
sd.widthAnchor.constraint(equalToConstant: 100),
sd.heightAnchor.constraint(equalToConstant: 40)
]
NSLayoutConstraint.activate(start)
sd.addTarget(self, action: #selector(moveRight), for: .allEvents)
@objc func moveRight()
NSLayoutConstraint.deactivate(start)
let jessicaAlba = CGFloat(sd.value)
print(jessicaAlba)
NSLayoutConstraint.activate ([
pic.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
pic.topAnchor.constraint(equalTo: view.centerYAnchor, constant : -225),
pic.widthAnchor.constraint(equalToConstant: jessicaAlba),
pic.heightAnchor.constraint(equalToConstant: jessicaAlba),
sd.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
sd.topAnchor.constraint(equalTo: view.centerYAnchor, constant : +250),
sd.widthAnchor.constraint(equalToConstant: 100),
sd.heightAnchor.constraint(equalToConstant: 40)
])
NSLayoutConstraint.activate(change)
【问题讨论】:
【参考方案1】:您的代码有两个问题。
1 ) 您已将 widthAnchor 和 heightAnchor 约束设置为 CGFloat(sd.value) 的常量,范围在 0 到 1 之间。这就是为什么您的图片似乎消失了。但实际上,它的宽度和高度被设置为小于 1 的值。
2 ) 您尚未从 moveRight 函数停用先前设置的约束。
试试下面的示例 sn-p,
@objc func moveRight()
NSLayoutConstraint.deactivate(start)
let jessicaAlba = 300 + ( 300 * CGFloat(sd.value) )
print(CGFloat(sd.value))
start = [
pic.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
pic.topAnchor.constraint(equalTo: view.centerYAnchor, constant : -225),
pic.widthAnchor.constraint(equalToConstant: jessicaAlba),
pic.heightAnchor.constraint(equalToConstant: jessicaAlba),
sd.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :150),
sd.topAnchor.constraint(equalTo: view.centerYAnchor, constant : +250),
sd.widthAnchor.constraint(equalToConstant: 100),
sd.heightAnchor.constraint(equalToConstant: 40)
]
NSLayoutConstraint.activate (start)
【讨论】:
以上是关于使用滑块控制 nslayoutConstraint 的宽度和高度的主要内容,如果未能解决你的问题,请参考以下文章