1、UITextField
let textField = UITextField(frame: CGRect(x: 10, y: 60, 200, height: 30)) //设置边框样式 textField.borderStyle = .roundedRect //修改圆角半径的话需要将maskToBounds设置为true textField.layer.masksToBounds = true textField.layer.cornerRadius = 12.0 textField.layer.borderWidth = 2.0 textField.layer.borderColor = UIColor.red.cgColor //文本提示框文字 textField.placeholder = "请输入用户名" //当文字超出文本框宽度时,自动调整文字大小 textField.adjustsFontSizeToFitWidth = true //最小可缩小的字号 textField.minimumFontSize = 14 //文字对齐 水平 textField.textAlignment = .center //文字对齐 垂直 textField.contentVerticalAlignment = .top textField.contentHorizontalAlignment = .center; //背景图片设置 textField.borderStyle = .none//先要除去边框样式 textField.background = UIImage.init(named: "back") //清除按钮 textField.clearButtonMode = .whileEditing//编辑时出现清除按钮 //密码输入框 textField.isSecureTextEntry = true//输入框会显示成小黑点 //设置文本框关联的键盘类型 textField.keyboardType = .numberPad//数字键盘 //使文本框变成第一响应者 textField.becomeFirstResponder() //使文本框失去焦点,并收回键盘 textField.resignFirstResponder() //设置键盘return键的样式 textField.returnKeyType = .send self.view.addSubview(textField)
2、UITextView
override func viewDidLoad() { super.viewDidLoad() let textView = UITextView(frame: CGRect(x: 10, y: 100, 200, height: 100)) textView.layer.borderWidth = 1 textView.layer.borderColor = UIColor.gray.cgColor //是否可以编辑 textView.isEditable = false; //内容是否可选 textView.isSelectable = false //给文字中的号码和网址自动加链接 textView.dataDetectorTypes = []//什么不加 textView.dataDetectorTypes = .phoneNumber//只有电话加链接 textView.dataDetectorTypes = .link//只有网址加链接 textView.dataDetectorTypes = .all//电话和网址都加 self.view .addSubview(textView) //自定义选择内容后的菜单 let mail = UIMenuItem(title: "邮件", action:#selector(ViewController.onMail)) let weixin = UIMenuItem(title: "微信", action: #selector(ViewController.onWeiXin)) let menu = UIMenuController() menu.menuItems = [mail,weixin] } @objc func onMail(){ print("maill") } @objc func onWeiXin(){ print("weixin") }
3、UISwitch
var uiswitch:UISwitch! override func viewDidLoad() { super.viewDidLoad() uiswitch = UISwitch() //设置位置(开关大小无法设置) uiswitch.center = CGPoint(x:100, y:50) //设置默认值 uiswitch.isOn = true; uiswitch.addTarget(self, action: #selector(switchDidChange), for:.valueChanged) self.view.addSubview(uiswitch); } @objc func switchDidChange(){ //打印当前值 print(uiswitch.isOn) }