ios - 使用 NSLayout 设置 UILabel 的 X 和 Y 值

标签 ios iphone swift user-interface nslayoutconstraint

我正在添加一个 UI 标签,我正在尝试编程 UI 代码。我使用以下代码设置标签:

let titleLabel: UILabel = {
    let lb = UILabel()
    lb.translatesAutoresizingMaskIntoConstraints = false
    lb.textAlignment = .center
    lb.numberOfLines = 1
    lb.textColor = UIColor.black
    lb.font=UIFont.systemFont(ofSize: 22)
    lb.backgroundColor = UIColor.white
    return lb

然后使用此代码添加约束:

func setupTitleLabel() {


    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
    titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
    titleLabel.centerXAnchor.constraint(equalTo: titleLabel.superview!.centerXAnchor).isActive = true
    titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true
}

我稍后会调用此函数。但是,我不确定如何更改为 X 和 Y 值。目前,X 和 Y 都将它设置在页面中间,但我如何将它移到顶部。

最佳答案

正如我在评论中所说,如果您需要将标签固定到标签 super View 的顶部,则您错误地使用了 titleLabel.superview!.centerYAnchor,您需要使用 titleLabel.superview!。 topAnchor 代替

替换这个

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true

通过这个

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true

关于ios - 使用 NSLayout 设置 UILabel 的 X 和 Y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45806837/

相关文章:

iphone - 如何在将新行添加到 UITextView 实例时向上 ScrollView ?

ios - Spotify iOS SDK Beta 25 在真实设备上没有声音

ios - 如何使用 AVMutableCompositionTrack 合并音频和视频

ios - 以编程方式返回到 Swift 中的上一个 ViewController

iphone - 如何使用 TTStyledTextLabel?

swift - titleLabel.text 与 Swift 中的 currentTitle

php - 如何在 Swift 3 中将值作为 NSDictionary 获取?

ios - 避免 nil slider 值?

ios - react-native-fetch-blob IOS API openDocument 不工作

ios - UISearchController : search bar initially too wide