2017-07-30 92 views
0

我想對齊分段控制權添加到`的UITableViewCell這樣的:添加右對齊約束的編程方式添加子視圖

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "mycell") 
    // ... 
    addSegmentedControlToCell(cell) 
    // ... 

然後

func addSegmentedControlToCell(_ cell:UITableViewCell){ 
    let items = ["One","Two"] 
    let unitControl = UISegmentedControl(items: items) 
    unitControl.selectedSegmentIndex = 0 
    let maxWd = cell.frame.size.width 
    let maxHt = cell.frame.size.height 
    let padding:CGFloat = 5 
    unitControl.frame = CGRect(x:maxWd/2, y:padding, width:maxWd/2, height: maxHt-padding*2) 
    unitControl.addTarget(self, action: #selector(SettingsTableViewController.unitControlValueDidChange(_:)), for: .valueChanged) 
    cell.addSubview(unitControl) 
} 

這非常適用於我的默認設備的iPhone 6.但是,當我運行這個應用程序在一個較小的寬度的設備,如iPhone 5,編程添加段控制,接收50%的單元格寬度(cell.frame.size.width/2)似乎遠大於50寬度的百分比並在單元視圖端口下向右延伸。

這是因爲我看到自動佈局和約束,因爲iPhone 5單元格視圖被調整大小。所以我正在嘗試向我的新Segment Control添加一個約束,該約束與app crush失敗。請注意,我不太擅長以編程方式添加約束。

let widthContr = NSLayoutConstraint(item: unitControl, 
             attribute: NSLayoutAttribute.width, 
             relatedBy: NSLayoutRelation.equal, 
             toItem: cell, 
             attribute: NSLayoutAttribute.notAnAttribute, 
             multiplier: 1, 
             constant: 0.5) 
    cell.addConstraints([widthContr]) 

如何正確對齊子視圖(段控制)的正確的單元格大小?

回答

0

您可以設定限制這樣的:

yourView.rightAnchor.constraint(equalTo: yourCell.rightAnchor, constant: -10).isActive = true 

或者:

yourView.heightAnchor.constraint(equalToConstant: 50).isActive = true 

但要確保你有這樣的代碼:

yourSegmentedControl.translatesAutoresizingMaskIntoConstraints = false 
0

您可以通過三種方式做到這一點。 1)你在NSLayoutConstraint中寫入了0.5個常量(這是一個錯誤)。 你需要寫的常數是1,乘數應該是0.5。 2)或者你應該在Custom Cell的layoutSubviews()方法中更新UISegmentControl的幀。 3)或者你應該在UIS​​egmentControl添加到單元格之後編寫cell.layoutSubviews()。