Swift 4 移动 UIButton 的位置



我一直在搜索其他问题,但我读过的解决方案都不适合我。

我需要修改此代码,以便当按钮的标题更改时,它仍然与表中的其他一些项目对齐。该按钮以编程方式声明,如下所示:

internal func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section % 2 != 0 {
let frame : CGRect = tableView.frame
btnSelectAll = UIButton(frame: CGRect(x: frame.size.width-92, y: 0 , width: 100, height: 30))
btnSelectAll.setTitle(btnTitle, for: .normal)
btnSelectAll.setTitleColor(UIColor.blue, for: .normal)
let lblTitle : UILabel = UILabel(frame: CGRect(x: 19, y: 0, width: 120, height: 30))
btnSelectAll.addTarget(self, action:#selector(selectAllClicked(sender:)), for: .touchUpInside)
lblTitle.text = Constants.FILTER_DEPARTMENT_SECTION
lblTitle.font = UIFont.boldSystemFont(ofSize: 17)
let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
headerView.backgroundColor = UIColor.white
headerView.addSubview(btnSelectAll)
headerView.addSubview(lblTitle)
return headerView
}
return nil
}

我试图在这里更改它:

if filter[Constants.FILTER_DEPARTMENT_SECTION]?.count == department.count {
if let btnSelectAll = btnSelectAll {
let frame : CGRect = tableView.frame
let newFrame = CGRect(x: frame.size.width-150, y: 0 , width: 100, height: 30)
btnSelectAll.frame = newFrame
btnSelectAll.setTitle(Constants.DESELECT_ALL, for: .normal)
btnSelectAll.setNeedsDisplay()
}
}

不幸的是,我仍然无法让它移动。

使用btnSelectAll.sizeToFit()

正如苹果所说:

如果要调整当前视图的大小,使其使用最合适的空间量,请调用此方法。特定的 UIKit 视图根据自己的内部需求调整自身大小。在某些情况下,如果视图没有超级视图,则它可能会根据屏幕边界调整自身大小。因此,如果希望给定视图的大小调整为其父视图,则应在调用此方法之前将其添加到父视图中。

最新更新