【发布时间】:2016-12-13 21:26:32
【问题描述】:
(Swift3/iOS10)
我正在尝试使用rightView 属性在UITextField 中放置两个按钮(保存/取消)。我的基本设置代码(来自viewDidLoad)如下:
private func accesorizeRenameField() {
let saveButton = UIButton(type: .system)
saveButton.setImage(#imageLiteral(resourceName: "buttonCheckmark"), for: .normal)
saveButton.addTarget(self, action: #selector(renameSave), for: .touchUpInside)
saveButton.tintColor = UIColor(white: 0.15, alpha: 1)
let cancelButton = UIButton(type: .system)
cancelButton.setImage(#imageLiteral(resourceName: "buttonX"), for: .normal)
cancelButton.addTarget(self, action: #selector(renameCancel), for: .touchUpInside)
cancelButton.tintColor = UIColor(227, 34, 60, 1)
let container = UIView()
container.addSubview(saveButton)
container.addSubview(cancelButton)
container.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = UIColor.cyan
saveButton.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
cancelButton.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true
saveButton.heightAnchor.constraint(equalTo: container.heightAnchor).isActive = true
cancelButton.heightAnchor.constraint(equalTo: container.heightAnchor).isActive = true
saveButton.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
saveButton.trailingAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
cancelButton.leadingAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
cancelButton.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
self.renameField.rightView = container
self.renameField.rightViewMode = .always
}
稍后,当我通过一些动画暴露重命名字段时,我调用
self.renameField.rightView?.bounds = CGRect(x: 0, y: 0, width: self.renameField.bounds.height * 2, height: self.renameField.bounds.height)
self.renameField.rightView?.setNeedsLayout()
"rightView.frame \(self.renameField.rightView?.frame)".print()
self.renameField.rightView?.subviews.enumerated().forEach() {index,child in
"child \(index) frame \(child.frame)".print()
}
但是,我无法显示按钮。青色背景(用于调试)出现,但实际上是正方形(应该是 2:1 矩形)。 print 显示子视图的帧大小为 0。正确的/惯用方法是什么?我觉得我只是在这里扔锤子......
【问题讨论】:
-
UIView 和按钮应该将它们的 translatesAutoresizingMaskIntoConstraints 设置为 false。我会试验一下,看看你是否可以得到一个带有彩色背景的普通 UIView 来显示(我似乎记得 textField 希望这个视图是方形的,大小类似于 44x44,但不确定)。
标签: ios swift uitextfield uikit overlay