也许您更喜欢这个解决方案
extension UIView {
enum Visibility {
case visible
case invisible
case gone
}
var visibility: Visibility {
get {
let constraint = (self.constraints.filter{$0.firstAttribute == .height && $0.constant == 0}.first)
if let constraint = constraint, constraint.isActive {
return .gone
} else {
return self.isHidden ? .invisible : .visible
}
}
set {
if self.visibility != newValue {
self.setVisibility(newValue)
}
}
}
private func setVisibility(_ visibility: Visibility) {
let constraint = (self.constraints.filter{$0.firstAttribute == .height && $0.constant == 0}.first)
switch visibility {
case .visible:
constraint?.isActive = false
self.isHidden = false
break
case .invisible:
constraint?.isActive = false
self.isHidden = true
break
case .gone:
if let constraint = constraint {
constraint.isActive = true
} else {
let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0)
self.addConstraint(constraint)
constraint.isActive = true
}
}
}
}
那么使用方法如下:
someView.visibility = .visible
someView.visibility = .invisible
someView.visibility = .gone
编辑:
提升能力:将从故事板中工作(只需写:“可见”,“不可见”,“隐藏”)在“可见状态”中。
所有视图内的约束都应小于1000
extension UIView {
enum Visibility: String {
case visible = "visible"
case invisible = "invisible"
case gone = "gone"
}
var visibility: Visibility {
get {
let constraint = (self.constraints.filter{$0.firstAttribute == .height && $0.constant == 0}.first)
if let constraint = constraint, constraint.isActive {
return .gone
} else {
return self.isHidden ? .invisible : .visible
}
}
set {
if self.visibility != newValue {
self.setVisibility(newValue)
}
}
}
@IBInspectable
var visibilityState: String {
get {
return self.visibility.rawValue
}
set {
let _visibility = Visibility(rawValue: newValue)!
self.visibility = _visibility
}
}
private func setVisibility(_ visibility: Visibility) {
let constraints = self.constraints.filter({$0.firstAttribute == .height && $0.constant == 0 && $0.secondItem == nil && ($0.firstItem as? UIView) == self})
let constraint = (constraints.first)
switch visibility {
case .visible:
constraint?.isActive = false
self.isHidden = false
break
case .invisible:
constraint?.isActive = false
self.isHidden = true
break
case .gone:
self.isHidden = true
if let constraint = constraint {
constraint.isActive = true
} else {
let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0)
self.addConstraint(constraint)
constraint.isActive = true
}
self.setNeedsLayout()
self.setNeedsUpdateConstraints()
}
}
}
subView.isHidden = true
- RajeshKumar R