簡體   English   中英

將UILabel居中於UITableView標頭中

[英]Centering a UILabel inside of a UITableView Header

我將UIView作為UITableView標頭添加,但是當我這樣做時,我的約束就崩潰了。 我正在嘗試將我的chapterVerseLabel在圓圈內,如下所示:

在此處輸入圖片說明

到目前為止,我是這樣做的:

    var allConstraints = [NSLayoutConstraint]()
    let views = ["tableView" : tableView, "containerView" : containerView, "chapterVerseLabel" : chapterVerseLabel]
    allConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-70-[chapterVerseLabel]-70-|", options: [], metrics: nil, views: views)
    NSLayoutConstraint.activateConstraints(allConstraints)

但是我不確定如何使它居中。 似乎所有嘗試將它居中的嘗試都沒有遵守在UITableView Header中居中的更嚴格的規則。

歡迎所有想法。


更新資料

我嘗試添加.CenterX值:

    let leftConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
    containerView.addConstraint(leftConstraint)
    let rightConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterX, relatedBy: .Equal, toItem: containerView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
    containerView.addConstraint(rightConstraint)

但這是結果:

在此處輸入圖片說明

現在,ChapterVerseLabel位於我的containerView中,該容器被分配為tableView.tableHeaderView 像這樣:

tableView.tableHeaderView = containerView

有任何想法嗎?

約束的問題在於,您已經通過給出頂部和底部約束來限制標簽​​。 另外,我也看不到前導約束和尾隨約束,實際上您必須根據需要垂直或水平對齊標簽,或同時對齊兩者。

NSLayoutConstraint *yCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
[containerView addConstraint:yCS];

NSLayoutConstraint *xCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
[containerView addConstraint:xCS];

假設containerView是您的標頭視圖,它是從headerforView委托方法返回的。 您需要為標簽提供高度和寬度。

中心有一個uiview。 如果要向中心的圓形視圖添加視圖(1/4),則無法使用視覺格式。 我假設您想將chapterVerseLabel 所以:

chapterVerseLabel.translatesAutoresizingMaskIntoConstraints = false
yourCircularView.addsubView(chapterVerseLabel)
let xCenterConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterX, relatedBy: .Equal, toItem: view2, attribute: .CenterX, multiplier: 1, constant: 0)
superview.addConstraint(xCenterConstraint)

let yCenterConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterY, relatedBy: .Equal, toItem: view2, attribute: .CenterY, multiplier: 1, constant: 0)
superview.addConstraint(yCenterConstraint)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM