Search code examples
iosswiftuikit

Swift 4 Move Location of UIButton


I've been searching all around the other questions but none of the solutions I've read worked for me.

I have this code I need to modify so that when the button's title changes, it still appears to be aligned with some other items in the table. The button was declared programmatically as shown below:

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
}

I tried to change it like so here:

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()
    }
}

Unfortunately I still can't get it to move.


Solution

  • Use btnSelectAll.sizeToFit(),

    As Apple says:

    Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.