我創建了一個自定義的UITableViewCell,它以編程方式添加到我的視圖控制器中。自定義單元格包含一個按鈕。問題是我無法實現在所有設備上居中對齊的按鈕。如果它是5s模擬器,並且我使用self.frame.width作爲按鈕框架的x座標,那麼它將居中 - 但不在6或6s上,但是如果我使用super.frame.width作爲x-coord ,然後以6模擬器爲中心。有誰知道我可以如何讓它集中在所有設備屏幕上?這裏是我的自定義按鈕的代碼,我簡單地返回它作爲一個UITableViewCell中的tableView委託在我的ViewController ...UIButton不能以UITableViewCell中的所有設備爲中心 - Swift
import Foundation
import UIKit
public class ButtonCell: UITableViewCell {
//Custom button to be added to the last cell to submit
let buttonImage = UIImage(named: "add_pub_button") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
/**
Creates the ButtonCell
- parameter style: A constant indicating a cell style. See UITableViewCellStyle for descriptions of these constants.
- parameter reuseIdentifier: A string used to identify the cell object if it is to be reused for drawing multiple rows of a table view. Pass nil if the cell object is not to be reused. You should use the same reuse identifier for all cells of the same form.
- returns: An initialized TextInputCell object or nil if the object could not be created.
*/
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
private func setup() {
//Overhangs the view slightly to avoid invalid constraints.
self.clipsToBounds = true
self.backgroundView = nil
self.backgroundColor = nil
self.tintColor = nil
self.selectionStyle = .None
button.frame = CGRectMake((self.frame.width - 134)/2, 0, 134, 44)
button.tintColor = nil
button.backgroundColor = nil
button.setImage(buttonImage, forState: .Normal)
self.contentView.addSubview(button)
}
/**
Needed for initialization from a storyboard.
- parameter aDecoder: An unarchiver object.
- returns: An initialized ButtonCell object or nil if the object could not be created.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
爲什麼不將按鈕添加到故事板中的第二個原型單元格,並使用「自動佈局」將其居中? – 2016-02-12 07:31:30
我有很多具有自定義事物,如擴展日期選擇器/常規選擇器/文本字段......有可能添加一個原型單元格出現在其他按鈕下方的tableView的按鈕下方。 – coopwatts
當然。每個原型單元都有一個標識符。您只需爲應顯示該按鈕的行出列按鈕故事板單元格即可。它可以讓你不必編寫或維護該代碼。 – 2016-02-12 07:38:35