我可以通过硬编码高度和宽度来更改按钮单击时UIView框架的高度和宽度,但是当我在CGFloat格式的UItext字段中从用户输入时,我无法更改它。
`
import UIKit
class SetBorderSizeViewController: UIViewController{
@IBOutlet weak var WidthText: UITextField!
@IBOutlet weak var Height: UITextField!
@IBOutlet weak var View_border: UIView!
override func viewDidLoad() {
super.viewDidLoad()
View_border.isHidden = true
}
//Change UIView Height and width frame on "ChangeSizeButton" Button Press.....
@IBAction func ChangeSizeButton(_ sender: Any) {
View_border.isHidden = false
View_border.layer.borderWidth = 5
/// Here i want to get user input from text field...
View_border.frame.size.height = 20
View_border.frame.size.width = 80
}
}
`
任何人都可以根据我的要求更新我的代码???
答案 0 :(得分:0)
试试这个:
@IBAction func ChangeSizeButton(_ sender: Any) {
View_border.isHidden = false
View_border.layer.borderWidth = 5
/// Here i want to get user input from text field...
View_border.frame.size.height = CGFloat(Float(WidthText.text!)!)
View_border.frame.size.width = CGFloat(Float(Height.text!)!)
self.View_border.layoutIfNeeded()
}
答案 1 :(得分:0)
此代码也有效:
class ViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet private weak var resizableView: UIView!
@IBOutlet private weak var widthTextField: UITextField!
@IBOutlet private weak var heightTextField: UITextField!
// MARK: IBActions
@IBAction private func didResizeButtonTapped(_ sender: UIButton) {
let (newWidth, newHeight) = convertValues()
resizableView.frame.size.width = newWidth
resizableView.frame.size.height = newHeight
}
}
// MARK: Private Methods
private extension ViewController {
func convertValues() -> (width: CGFloat, height: CGFloat) {
let width = Float(widthTextField.text ?? "0")
let height = Float(heightTextField.text ?? "0")
return (CGFloat(width ?? 0.0), CGFloat(height ?? 0.0))
}
}
但在我的情况下,我使用约束为我的“resizableView”,所以我的视图每次都无效。在这种情况下,您可以为宽度和高度约束创建参考,并将它们设置为新值,如:
widthConstraint.constant = <your_value>