Swift 4.1与Xcode 9.3.1中NSLayoutYAxisAnchor无constraint成员报错
解决Auto Layout Anchor API报错:
Value of type 'NSLayoutYAxisAnchor' has no member 'constraint' 这个问题我之前在Swift 4.1 + Xcode 9.3.1的环境下也踩过坑!其实根源特别简单——你的代码没有正确关联UIKit框架,导致编译器识别的是Foundation里的基础NSLayoutYAxisAnchor类,而这个基础类根本没有constraint方法。UIKit才给这些Anchor类扩展了我们常用的Auto Layout约束创建方法。
具体解决方案:
第一步:检查是否导入UIKit
打开你的代码文件,确认顶部有这句导入:import UIKit很多时候新建Swift文件默认只导入
Foundation,尤其是自定义View、Cell这类文件,忘了加import UIKit就会触发这个报错。第二步:确认类的继承关系
确保你的代码所在的类是UIKit相关类的子类,比如:- 自定义View要继承
UIView - 自定义TableViewCell要继承
UITableViewCell - ViewController要继承
UIViewController
举个正确的自定义View写法示例:
import UIKit class CustomContentView: UIView { let contentView = UIView() override init(frame: CGRect) { super.init(frame: frame) setupLayout() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayout() } private func setupLayout() { addSubview(contentView) contentView.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 9.0, *) { contentView.topAnchor.constraint(equalTo: topAnchor).isActive = true contentView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true contentView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true contentView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } } }只有继承UIKit的类,
topAnchor、widthAnchor这些属性才是UIKit扩展后的版本,自带constraint方法。- 自定义View要继承
另外,针对你第二个按钮约束的代码,还要提一句:尽量不要用frame.width来设置约束常量,因为frame在Auto Layout生效前可能还没有正确的值,建议用其他Anchor或者固定数值替代,避免布局异常。
内容的提问来源于stack exchange,提问作者niravdesai21
相关产品推荐
相关产品推荐

