自定义UIView类 – Swift
我已经build立了一个视图,从底部出现,并在一段时间后隐藏,它运作良好,但我想在UIView
类作为一种模式,我看着互联网,但我不明白如何做到这一点。
snake = UIView(frame: CGRect(x: 0 , y: self.view.frame.size.height-66, width: self.view.frame.size.width, height: 66)) snake.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0) let label = UILabel(frame: CGRect(x: 12, y: 8, width: snake.frame.size.width-90, height: 50)) label.text = "Connection error please try again later!!" label.textColor = UIColor.whiteColor() label.numberOfLines = 0 label.font = UIFont.systemFontOfSize(14) snake.addSubview(label) let button = UIButton(frame: CGRect(x: snake.frame.size.width-87, y: 8, width: 86, height: 50)) button.setTitle("OK", forState: UIControlState.Normal) button.setTitleColor(UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1.0), forState: UIControlState.Normal) button.addTarget(self, action: "hideSnackBar:", forControlEvents: UIControlEvents.TouchUpInside) snake.addSubview(button) self.view.addSubview(snake)
如何从这个类开始我不知道,我创build视图与框架的编程方式,我需要设置button的属性,例如或标签,并创build任何类的视图。
class snake: UIView { override init (frame : CGRect) { super.init(frame : frame) } convenience init () { self.init(frame:CGRect.zero) } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } }
码:
var label:UILabel! var button:UIButton! override init (frame : CGRect) { super.init(frame : frame) self.backgroundColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0) label = UILabel(frame: CGRect(x: 12, y: 8, width: self.frame.size.width-90, height: 50)) label.text = "Connection error please try again later!!" label.textColor = UIColor.whiteColor() label.numberOfLines = 0 label.font = UIFont.systemFontOfSize(14) self.addSubview(label) button = UIButton(frame: CGRect(x: self.frame.size.width-87, y: 8, width: 86, height: 50)) button.setTitle("OK", forState: UIControlState.Normal) button.setTitleColor(UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1.0), forState: UIControlState.Normal) button.addTarget(self, action: "hideSnackBar:", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(button) }
并使用它:
let snakeView = snake(frame: CGRectMake(0 ,self.view.frame.size.height-66, self.view.frame.size.width, 66)))
并为snakeview设置数据:
snakeView.label.text = "hello"
但通常我会创build一个函数来更新视图的数据:
func updateData(title:String){ self.label.text = title }
并在需要时调用它:
snake.updateData("hello")
P / s:如果使用xib,则必须执行awakeFromNib而不是init。 用xib创build蛇(记住xib的设置标识符:“snakeView”):
let snakeView = NSBundle.mainBundle().loadNibNamed("snakeView", owner: nil, options: nil)[0] as snakeView
- 停止UIView中的所有asynchronous任务
- CLLocationManager didUpdateLocations不被调用
- 核心数据迁移:无法将types“NSManagedObject_MyType”的值转换为“MyModule.MyType”
- 如何在xcode 7.3.1中使用iOS 10 UserNotifications框架swift 2.2?
- 使用Sinch的即时消息推送通知不在iOS上
- Alamofire 4和JSON中的特殊字符
- 定期更新位置背景Swift 3.0 iOS 10
- 命令/ bin / sh失败,退出代码1和embedded式pod框架
- 所有符合协议的类inheritance默认实现