2017-04-04 127 views
1

以编程方式,我创建了一个视图并向其添加了标签和按钮。它在垂直方向上很好,它与中心对齐,但是当我旋转屏幕时,它不对齐居中,而是看起来像左对齐。swift:标签和按钮文本的中心对齐方式

这是我的代码:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 


    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 150)) 
    headerView.layer.borderWidth = 1 
    headerView.layer.borderColor = UIColor.whiteColor().CGColor 
    headerView.backgroundColor = ClientConfiguration.primaryUIColor() 

    let myLabel = UILabel() 
    myLabel.frame = CGRectMake(-1, -1, tableView.frame.width, 30) 
    myLabel.font = UIFont.boldSystemFontOfSize(14) 
    myLabel.backgroundColor = ClientConfiguration.primaryUIColor() 
    myLabel.textColor = UIColor.whiteColor() 
    myLabel.text = "Select Time Zone" 
    myLabel.textAlignment = .Center 

    let frame = CGRectMake(1, 1,headerView.frame.width , 70) 
    self.btnTimeZone.frame = frame 
    headerView.addSubview(myLabel) 
    headerView.addSubview(self.btnTimeZone) 

    self.buttonTitileString = self.selectedZone.value  
    self.btnTimeZone.setTitle(buttonTitileString, forState: .Normal) 

    return headerView 

} 

In horizontal mode the button text and label are aligned to left

,当我设置self.btnTimeZone.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center

它在水平模式很好,但在垂直模式中都作为是右对齐; enter image description here

我该如何解决这个问题,我需要他们两个中心水平和垂直模式对齐。

+0

你可能要重新计算框架的方向改变时。当您更改方向时,宽度会更改为高度,反之亦然。如果您上传示例项目,也许我可以更好地审视它。另外,为什么你不使用自动布局? –

+0

这是我所做的所有创建视图Programitically。 – iron

回答

1

如果应用程序应支持纵向和横向模式,最好的方法是使用NSLayoutConstraint

当然,你可以选择以编程方式或从界面生成器创建它们,我想指出,你可以创建标题视图作为单元格,而不需要以编程方式进行;这显然会导致为头部子视图设置所需的限制。

+0

你能编辑以上我的代码,并显示我在哪里错了..? – iron

+0

为了确保我会给出一个有用的答案,我建议将它作为一个单元格(从storyboard)添加,而不是以编程方式进行。是否需要以编程方式进行? –

+0

yes of course我需要它 – iron

0

您只需在旋转手机时重新加载表格。实施以下方法并在此方法的内部重新加载表格

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { 

     tableView.reloadData() 

    } 
+0

是这个方法会自动调用。? – iron

+0

这不起作用 – iron

+0

是的。在ViewController中实现它。如果您有任何问题,请发表评论 – GayashanK

0

您可以尝试为父视图设置自动调整大小。

headerView.autoresizesSubviews = true 
myLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] 
self.btnTimeZone.autoresizingMask = [.flexibleWidth, .flexibleHeight] 
+0

这应该在返回标题视图之前使用 – iron

+0

仍然是同样的问题 – iron

+0

@iron,尝试在[这里更改autoresizingMask数组中的值](https://developer.apple.com/reference/uikit/uiviewautoresizing)。尝试使用保证金值 – svvoff

0

尝试,这也

变化

tableView.frame.width 

tableView.frame.size.width