我试图为UIView编写一个扩展,以便更容易地为视图设置锚点。
这样做的目的是编写一个类似于这样的setAnchors方法:
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结构一起工作?
发布于 2021-01-25 17:05:09
你可以用通用的。
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
}
}
}https://stackoverflow.com/questions/65888794
复制相似问题