我创建了一个自定义 UITableViewCell,它以编程方式添加到我的 View Controller 中。自定义单元格包含一个按钮。问题是我无法实现按钮在所有设备上居中。如果它是 5s 模拟器,并且我使用 self.frame.width 作为按钮框架的 x 坐标,那么它会居中 - 但不是在 6 或 6s 上,但如果我使用 super.frame.width 作为 x 坐标,然后以 6 模拟器为中心。有谁知道如何让它在所有设备屏幕上居中?这是我的自定义按钮的代码,我只需将其作为 UITableViewCell 返回到我的 View Controller 的 tableView 委托(delegate)中...
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()
}
}
最佳答案
只需在layoutSubviews
方法中设置框架相关操作
例如,
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
//no need of setting the frame of button hear
//at the time initialisation there is no frame available for cell
//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)
}
//set it hear because frame of the cell available hear
override func layoutSubviews() {
super.layoutSubviews()
button.frame = CGRectMake((self.frame.width - 134)/2, 0, 134, 44)
}
关于swift - UIButton 无法在 UITableViewCell 中的所有设备上居中 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356941/