學(xué)習(xí)Mac開發(fā)第四節(jié) 學(xué)習(xí)NSSlider
認(rèn)識NSSlider
層級結(jié)構(gòu) ? Inherits From: NSControl -> NSView -> NSResponder -> NSObject?
獲取NSSlider滑動后的值
拖拽到.m文件一個Action,可以獲取浮點型和整數(shù)型的值
- (IBAction)sliderAction:(id)sender {
NSSlider *slider = (NSSlider *)sender;
//self.sliderValue.stringValue = [NSString stringWithFormat:@"%f",slider.floatValue];
slider.stringValue = [NSString stringWithFormat:@"%ld",(long)slider.integerValue];
}
#import "MyCustomSlider.h"
@implementation MyCustomSlider
- (void)drawBarInside:(NSRect)rect flipped:(BOOL)flipped {
//? [super drawBarInside:rect flipped:flipped];
rect.size.height = 5.0;
// Bar radius
CGFloat barRadius = 2.5;
// Knob position depending on control min/max value and current control value.
CGFloat value = ([self doubleValue]? - [self minValue]) / ([self maxValue] - [self minValue]);
// Final Left Part Width
CGFloat finalWidth = value * ([[self controlView] frame].size.width - 8);
// Left Part Rect
NSRect leftRect = rect;
leftRect.size.width = finalWidth;
NSLog(@"- Current Rect:%@ \n- Value:%f \n- Final Width:%f", NSStringFromRect(rect), value, finalWidth);
// Draw Left Part
NSBezierPath* bg = [NSBezierPath bezierPathWithRoundedRect: rect xRadius: barRadius yRadius: barRadius];
[NSColor.orangeColor setFill];
[bg fill];
// Draw Right Part
NSBezierPath* active = [NSBezierPath bezierPathWithRoundedRect: leftRect xRadius: barRadius yRadius: barRadius];
[NSColor.purpleColor setFill];
[active fill];
}
@end
自定義Slider ?go to download custom slider
學(xué)習(xí)Mac開發(fā)第五節(jié) 學(xué)習(xí)objective-c 調(diào)用shell 腳本
NSString* shellPath = @"/Users/主機名/Desktop/tool/LSUnusedResources-master/simian/bin";
NSString* path =[shellPaht stringByAppendingString:@"/aksimian.sh"];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
//數(shù)組index 0 shell路徑, 如果shell 腳本有輸入?yún)?shù),可以加入數(shù)組里,index 1 可以輸入$1 @[path,@"$1"],依次延后。
NSArray *arguments =@[path];
[task setArguments: arguments];
[task launch];
學(xué)習(xí)Mac開發(fā)第六節(jié) ?學(xué)習(xí)NSOpenPanel 選擇路徑和創(chuàng)建文件夾
NSOpenPanel* panel = [NSOpenPanel openPanel];
__weak typeof(self)weakSelf = self;
//是否可以創(chuàng)建文件夾
panel.canCreateDirectories = YES;
//是否可以選擇文件夾
panel.canChooseDirectories = YES;
//是否可以選擇文件
panel.canChooseFiles = YES;
//是否可以多選
[panel setAllowsMultipleSelection:NO];
//顯示
[panel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result) {
//是否點擊open 按鈕
if (result == NSModalResponseOK) {
//NSURL *pathUrl = [panel URL];
NSString *pathString = [panel.URLs.firstObject path];
weakSelf.urlTextField.stringValue = pathString;
? ? ?}
}];
// 懸浮電腦主屏幕上
//? ? [panel beginWithCompletionHandler:^(NSInteger result) {
//
//? ? }];
學(xué)習(xí)Mac開發(fā)第七節(jié)?學(xué)習(xí)NSTableView Cell Base
創(chuàng)建列表
1.在故事版上的ViewContoller 上面拖拽個tablview 并且把列表代理拖拽到控制器上。
2.設(shè)置3個欄目如下圖
3.分別設(shè)置3個欄目名稱為ID ,name image
4.指定每個欄目對象cell的唯一標(biāo)識符
對應(yīng)如下
ID->userid name->username image->useravatar
把image下面的TextCell 修改為imageCell 用來顯示圖片
1.創(chuàng)建個UserDetailDataModel 數(shù)據(jù)Model 屬性名稱要和上面的標(biāo)識符對應(yīng)
#import@interface UserDetailDataModel : NSObject
@property (strong, nonatomic)NSString *userid;
@property (strong, nonatomic)NSString *username;
@property (strong, nonatomic)NSImage *useravatar;
@end
設(shè)置tablview delegate 和datasource
//? ViewController.m
//? NSTablviewDemo//
//? Created by wufeng on 17/05/28.//? Copyright ? 2017年 zhule.com. All rights reserved.
//#import "ViewController.h"
#import "UserDetailDataModel.h"
@interface ViewController ()@property (strong, nonatomic)NSMutableArray *dataSource;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dataSource = [NSMutableArray new];
//設(shè)置Cell 高度
[self.tablview setRowHeight:45];
//創(chuàng)建數(shù)據(jù)Model
NSArray *userIdArray = @[@"101",@"102",@"103",@"104"];
NSArray *userNameArray = @[@"Allen",@"Jack",@"Luck",@"Tony"];
NSArray *userAvatarArray = @[[NSImage imageNamed:@"tag_1.png"],[NSImage imageNamed:@"tag_2.jpg"],[NSImage imageNamed:@"tag_3.jpg"],[NSImage imageNamed:@"tag_4.jpeg"]];
for (NSInteger i = 0; i < userNameArray.count; i++) {
UserDetailDataModel *detail = [[UserDetailDataModel alloc]init];
detail.userid = userIdArray[i];
detail.username = userNameArray[i];
detail.useravatar = userAvatarArray[i];
[self.dataSource addObject:detail];
? }?
[self.tablview reloadData];
// Do any additional setup after loading the view.
}
#pragma mark TablviewDataSource
//cell 個數(shù)
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return? self.dataSource.count;
?}
//設(shè)置列表Value
- (nullable id)tableView:(NSTableView *)tableView objectValueForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row{
if([self.dataSource count] <= 0){
return nil;
? ? ? }
UserDetailDataModel *detail = self.dataSource[row];
return? [detail valueForKey: [tableColumn identifier]];
}
//cell綁定對象模型
- (void)tableView:(NSTableView *)tableView setObjectValue:(nullable id)object forTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row {
UserDetailDataModel *detail = self.dataSource[row];
[detail setValue:object forKey: [tableColumn identifier]];
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
列表高度設(shè)置
[self.tablview setRowHeight:45];
//或者
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{
return 45;
}
設(shè)置標(biāo)題居中
設(shè)置列表文字居中
設(shè)置Text Cell 居中模式
總覺得怪怪的,居然沒有上下居中這么能忍 Google 下,解決方案重寫NSTextFieldCell
#import <Cocoa/Cocoa.h>
@interface RSVerticallyCenteredTextFieldCell : NSTextFieldCell{
BOOL mIsEditingOrSelecting;
}
@end
#import "RSVerticallyCenteredTextFieldCell.h"
@implementation RSVerticallyCenteredTextFieldCell
- (NSRect)drawingRectForBounds:(NSRect)theRect{
// Get the parent's idea of where we should draw
NSRect newRect = [super drawingRectForBounds:theRect];
// When the text field is being
// edited or selected, we have to turn off the magic because it screws up
// the configuration of the field editor.? We sneak around this by
// intercepting selectWithFrame and editWithFrame and sneaking a
// reduced, centered rect in at the last minute.
if (mIsEditingOrSelecting == NO){
// Get our ideal size for current text
NSSize textSize = [self cellSizeForBounds:theRect];
// Center that in the proposed rect
float heightDelta = newRect.size.height - textSize.height;
? ? ? ? if (heightDelta > 0){
? ? ? ? ? newRect.size.height -= heightDelta;
? ? ? ? ? newRect.origin.y += (heightDelta / 2);
? ? ? ?}
?}
return newRect;
}
- (void)selectWithFrame:(NSRect)rect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(nullable id)delegate start:(NSInteger)selStart length:(NSInteger)selLength{
rect = [self drawingRectForBounds:rect];
mIsEditingOrSelecting = YES;
[super selectWithFrame:rect inView:controlView editor:textObj delegate:delegate start:selStart length:selLength];
mIsEditingOrSelecting = NO;
}
- (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject event:(NSEvent *)theEvent{
aRect = [self drawingRectForBounds:aRect];
mIsEditingOrSelecting = YES;
[super editWithFrame:aRect inView:controlView editor:textObj delegate:anObject event:theEvent];
mIsEditingOrSelecting = NO;
}
@end
修改成重寫的類
監(jiān)聽單擊事件
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification{
NSInteger currenSelectRow = [self.tablview selectedRow];
NSLog(@"selectRow=========%ld",(long)currenSelectRow);
}
添加雙擊事件
在viewDidLoad里面添加如下代碼
[self.tablview setDoubleAction:@selector(tableViewDoubleClicked)];
self.tablview.allowsEmptySelection =? YES;
學(xué)習(xí)mac開發(fā)第八節(jié) 10分鐘學(xué)會數(shù)據(jù)庫簡單操作
簡單介紹下我們將用什么數(shù)據(jù)庫,能在10分鐘就能會。 它就是Realm,在之前我從來沒用他開發(fā)。只是傳說聽過他的強大,居然在我簡單的看了一眼文檔居然就上手操作,我不在這里過分介紹他了,網(wǎng)上很多了,官網(wǎng)也有中文介紹。下面會總結(jié)我遇到的一些問題吧。realm 本身有很多強大的功能,本文只是花10分鐘在mac 開發(fā)中實踐了簡單的增刪改查
他的優(yōu)點很明顯:簡單、live objec、線程安全、懶加載、離線優(yōu)先
接入realm庫 采用了最簡單的方法下載后把庫拖到工程里,當(dāng)然你也可以采用cocoapods 方式
拖拽后確認(rèn)是否成功引入 如下圖
如果需要上傳AppStroe 需要創(chuàng)建RunScript 添加 下面。
bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework/strip-frameworks.sh"
要實現(xiàn)一個能夠錄入學(xué)生姓名,年齡,性別,地址,當(dāng)然還有一個唯一的學(xué)號
首先我們來創(chuàng)建一個學(xué)生對象
import Cocoa
import RealmSwift
class StudentModel: Object {
dynamic var studentName = ""
dynamic var studentAge = 0
dynamic var studentID? = 1
dynamic var studentSex = ""
dynamic var studentAddress = ""
//主鍵
override static func primaryKey() -> String? {
return "studentID"
? }
}
用學(xué)生的學(xué)號當(dāng)做唯一的主鍵,方便我們快速查詢。
下面搭建個簡單的頁面
下面是簡單的添加方法
//把數(shù)據(jù)添加Realm 數(shù)據(jù)庫中
func addStudent() {
//沒有自增主鍵
let lastStudent = realm.objects(StudentModel.self).sorted(byKeyPath:"studentID", ascending: true).last
let studentModel = StudentModel()
studentModel.studentAge = Int(self.ageTextField.intValue)
studentModel.studentSex = self.sex!
studentModel.studentAddress = self.addressTextField.stringValue
studentModel.studentName =? self.nameTextField.stringValue
if lastStudent?.studentID != nil {
studentModel.studentID = lastStudent!.studentID + 1
? ?}else {
studentModel.studentID = 1;
? ?}
weak var weakSelf = self
try! realm.write {
realm.add(studentModel)
weakSelf?.hintLable.stringValue = "添加成功"
? ? }
}
我最初的想法是主鍵自增,后來沒有發(fā)現(xiàn)相對應(yīng)的Api.只能排序后去找最后一個學(xué)生的學(xué)號加一當(dāng)前學(xué)生的學(xué)號。因為 Realm 是一個 MVCC 數(shù)據(jù)庫 ,底層用 C++ 編寫。MVCC 指的是多版本并發(fā)控制。這樣的機制導(dǎo)致沒法自增主鍵。如果敢興趣可以看其他文章詳情介紹。
官網(wǎng)提供了Realm Browse 工具,方便查看數(shù)據(jù)庫的改變。 我們可以通過下面代碼找到數(shù)據(jù)庫的位置
print(("Path to realm file: " + realm.configuration.fileURL!.absoluteString))
增加
下面我們添加一名學(xué)生吧 學(xué)生studentID 為 1
下面通過學(xué)生studentID = 1 條件查詢這個學(xué)生的信息
//全局變量lazy var realm = try! Realm()
//查詢學(xué)生的modelvar item:StudentModel! = nil
//搜索結(jié)果集合var searchValue:Results?
查詢
searchValue = realm.objects(StudentModel.self).filter("studentID = %d",studentValue!)
self.item = searchValue![0]
或者 也可以用NSPredicate 方式查詢
let predicate = NSPredicate(format: "studentID = %d",studentValue)
searchValue = realm.objects(StudentModel.self).filter(predicate)
查詢的核心代碼就一句。但是很遺憾我沒有發(fā)現(xiàn)可以到直接返回對象而不是集合的方法.如何你發(fā)現(xiàn)了留言告訴我一聲,有時間我在查查資料。
修改
修改下查詢后人員的地址把china 改成USA 代碼如下
try!? realm.write {
self.item.studentAddress = self.changAddressTextField.stringValue;
}
刪除
try! realm.write {
if self.item != nil {
realm.delete(self.item)
?}
}
// Delete all objects from the realm
try! realm.write {
realm.deleteAll()
}
學(xué)習(xí)Mac開發(fā)第十節(jié) Image Well
簡單翻譯的一下:以允許用戶拖拽一張圖片放到這個圖片視圖上。
如果你用一個圖片壓縮軟件就會發(fā)現(xiàn),用戶可以直接拖拽一張圖片放上去就顯示的功能。
下面我們在storyboard 拖拽一個吧,居中顯示,并且設(shè)置一個默認(rèn)的圖片吧,來表示用戶可以添加圖片。
運行起來發(fā)現(xiàn)拖拽圖片沒有效果,那就查看下API。
已經(jīng)說的很清楚了 editable = Yes 時候才可以拖拽。
在屬性面板上就有這個屬性,點下勾就可以。
這時候我們發(fā)現(xiàn)就可以輕松的拖拽個圖片到上面去了。
當(dāng)我選中后點擊delete鍵 后刪除圖片,后現(xiàn)默認(rèn)圖片也消失了。如果想保留默認(rèn)圖片可以判讀是否為空,空的時候在添加上去就可以了。
- (IBAction)touchImageView:(id)sender {
NSImage *defaultImage = [NSImage imageNamed:@"add"];
if (!self.imageWell.image) {
self.imageWell.image = defaultImage;
? }
}
當(dāng)然你也可以通過這個事件添加圖片。