问题描述
我正在尝试为 UIView 编写一个扩展程序,以便更轻松地为视图设置锚点。
import UIKit
extension UIView {
func setAnchors(top: Anchor? = nil,bottom: Anchor? = nil,leading: Anchor? = nil,trailing: Anchor? = nil) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top,let anchorType = top.type as? NSLayoutAnchor<NSLayoutYAxisAnchor>,let constant = top.constant {
let constraint = topAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let bottom = bottom,let anchorType = bottom.type as? NSLayoutAnchor<NSLayoutYAxisAnchor>,let constant = bottom.constant {
let constraint = bottomAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let leading = leading,let anchorType = leading.type as? NSLayoutAnchor<NSLayoutXAxisAnchor>,let constant = leading.constant {
let constraint = leadingAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let trailing = trailing,let anchorType = trailing.type as? NSLayoutAnchor<NSLayoutXAxisAnchor>,let constant = trailing.constant {
let constraint = trailingAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
}
}
struct Anchor {
var type: NSLayoutAnchor<AnyObject>
var constant: CGFloat? = 0.0
}
可以这样调用:
topView.setAnchors(top: Anchor(type: view.topAnchor),leading: Anchor(type: view.leadingAnchor),trailing: Anchor(type: view.trailingAnchor))
我收到以下错误:
无法将“NSLayoutAnchor”类型的值转换为 预期的参数类型 'NSLayoutAnchor'
我知道我可以将 topAnchor 指定为 NSLayoutYAxisAnchor
等,并将常量也作为参数提供给此方法以使其工作,但我想知道是否有办法使其与此 Anchor 结构一起使用?
解决方法
您可以使用通用。
struct Anchor<T: AnyObject>{
var type: NSLayoutAnchor<T>
var constant: CGFloat? = 0.0
}
extension UIView {
func setAnchors<T: AnyObject>(top: Anchor<T>? = nil,bottom: Anchor<T>? = nil,leading: Anchor<T>? = nil,trailing: Anchor<T>? = nil) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top,let anchorType = top.type as? NSLayoutAnchor<NSLayoutYAxisAnchor>,let constant = top.constant {
let constraint = topAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let bottom = bottom,let anchorType = bottom.type as? NSLayoutAnchor<NSLayoutYAxisAnchor>,let constant = bottom.constant {
let constraint = bottomAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let leading = leading,let anchorType = leading.type as? NSLayoutAnchor<NSLayoutXAxisAnchor>,let constant = leading.constant {
let constraint = leadingAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
if let trailing = trailing,let anchorType = trailing.type as? NSLayoutAnchor<NSLayoutXAxisAnchor>,let constant = trailing.constant {
let constraint = trailingAnchor.constraint(equalTo: anchorType,constant: constant)
constraint.isActive = true
}
}
}